Use getters in MTP classes.

This commit is contained in:
John Preston 2019-07-05 15:38:38 +02:00
parent 3ca28c0cf9
commit 567bf60644
100 changed files with 2807 additions and 2672 deletions

File diff suppressed because it is too large Load diff

View file

@ -532,7 +532,7 @@ bool AuthSession::validateSelf(const MTPUser &user) {
if (user.type() != mtpc_user || !user.c_user().is_self()) { if (user.type() != mtpc_user || !user.c_user().is_self()) {
LOG(("API Error: bad self user received.")); LOG(("API Error: bad self user received."));
return false; return false;
} else if (user.c_user().vid.v != userId()) { } else if (user.c_user().vid().v != userId()) {
LOG(("Auth Error: wrong self user received.")); LOG(("Auth Error: wrong self user received."));
crl::on_main(this, [] { Core::App().logOut(); }); crl::on_main(this, [] { Core::App().logOut(); });
return false; return false;

View file

@ -353,14 +353,14 @@ void AddContactBox::onImportDone(const MTPcontacts_ImportedContacts &res) {
if (!isBoxShown() || !App::main()) return; if (!isBoxShown() || !App::main()) return;
const auto &d = res.c_contacts_importedContacts(); const auto &d = res.c_contacts_importedContacts();
Auth().data().processUsers(d.vusers); Auth().data().processUsers(d.vusers());
const auto &v = d.vimported.v; const auto &v = d.vimported().v;
const auto user = [&]() -> UserData* { const auto user = [&]() -> UserData* {
if (!v.isEmpty()) { if (!v.isEmpty()) {
auto &c = v.front().c_importedContact(); auto &c = v.front().c_importedContact();
if (c.vclient_id.v == _contactId) { if (c.vclient_id().v == _contactId) {
return Auth().data().userLoaded(c.vuser_id.v); return Auth().data().userLoaded(c.vuser_id().v);
} }
} }
return nullptr; return nullptr;
@ -380,7 +380,7 @@ void AddContactBox::onImportDone(const MTPcontacts_ImportedContacts &res) {
void AddContactBox::onSaveUserDone(const MTPcontacts_ImportedContacts &res) { void AddContactBox::onSaveUserDone(const MTPcontacts_ImportedContacts &res) {
auto &d = res.c_contacts_importedContacts(); auto &d = res.c_contacts_importedContacts();
Auth().data().processUsers(d.vusers); Auth().data().processUsers(d.vusers());
closeBox(); closeBox();
} }
@ -544,9 +544,9 @@ void GroupInfoBox::createGroup(
| [](auto updates) -> std::optional<const QVector<MTPChat>*> { | [](auto updates) -> std::optional<const QVector<MTPChat>*> {
switch (updates->type()) { switch (updates->type()) {
case mtpc_updates: case mtpc_updates:
return &updates->c_updates().vchats.v; return &updates->c_updates().vchats().v;
case mtpc_updatesCombined: case mtpc_updatesCombined:
return &updates->c_updatesCombined().vchats.v; return &updates->c_updatesCombined().vchats().v;
} }
LOG(("API Error: unexpected update cons %1 " LOG(("API Error: unexpected update cons %1 "
"(GroupInfoBox::creationDone)").arg(updates->type())); "(GroupInfoBox::creationDone)").arg(updates->type()));
@ -559,7 +559,7 @@ void GroupInfoBox::createGroup(
: std::nullopt; : std::nullopt;
} }
| [](auto chats) { | [](auto chats) {
return Auth().data().chat(chats->front().c_chat().vid.v); return Auth().data().chat(chats->front().c_chat().vid().v);
} }
| [&](not_null<ChatData*> chat) { | [&](not_null<ChatData*> chat) {
if (!image.isNull()) { if (!image.isNull()) {
@ -653,9 +653,9 @@ void GroupInfoBox::createChannel(const QString &title, const QString &descriptio
| [](auto updates) -> std::optional<const QVector<MTPChat>*> { | [](auto updates) -> std::optional<const QVector<MTPChat>*> {
switch (updates->type()) { switch (updates->type()) {
case mtpc_updates: case mtpc_updates:
return &updates->c_updates().vchats.v; return &updates->c_updates().vchats().v;
case mtpc_updatesCombined: case mtpc_updatesCombined:
return &updates->c_updatesCombined().vchats.v; return &updates->c_updatesCombined().vchats().v;
} }
LOG(("API Error: unexpected update cons %1 (GroupInfoBox::createChannel)").arg(updates->type())); LOG(("API Error: unexpected update cons %1 (GroupInfoBox::createChannel)").arg(updates->type()));
return std::nullopt; return std::nullopt;
@ -666,7 +666,7 @@ void GroupInfoBox::createChannel(const QString &title, const QString &descriptio
: std::nullopt; : std::nullopt;
} }
| [](auto chats) { | [](auto chats) {
return Auth().data().channel(chats->front().c_channel().vid.v); return Auth().data().channel(chats->front().c_channel().vid().v);
} }
| [&](not_null<ChannelData*> channel) { | [&](not_null<ChannelData*> channel) {
auto image = _photo->takeResultImage(); auto image = _photo->takeResultImage();
@ -681,7 +681,7 @@ void GroupInfoBox::createChannel(const QString &title, const QString &descriptio
)).done([=](const MTPExportedChatInvite &result) { )).done([=](const MTPExportedChatInvite &result) {
_creationRequestId = 0; _creationRequestId = 0;
if (result.type() == mtpc_chatInviteExported) { if (result.type() == mtpc_chatInviteExported) {
auto link = qs(result.c_chatInviteExported().vlink); auto link = qs(result.c_chatInviteExported().vlink());
_createdChannel->setInviteLink(link); _createdChannel->setInviteLink(link);
} }
if (_channelDone) { if (_channelDone) {
@ -1261,7 +1261,7 @@ RevokePublicLinkBox::Inner::Inner(QWidget *parent, Fn<void()> revokeCallback) :
MTP_flags(0) MTP_flags(0)
)).done([=](const MTPmessages_Chats &result) { )).done([=](const MTPmessages_Chats &result) {
const auto &chats = result.match([](const auto &data) { const auto &chats = result.match([](const auto &data) {
return data.vchats.v; return data.vchats().v;
}); });
for (const auto &chat : chats) { for (const auto &chat : chats) {
if (const auto peer = Auth().data().processChat(chat)) { if (const auto peer = Auth().data().processChat(chat)) {
@ -1364,7 +1364,7 @@ void RevokePublicLinkBox::Inner::mouseReleaseEvent(QMouseEvent *e) {
if (_revokeRequestId) return; if (_revokeRequestId) return;
_revokeRequestId = request(MTPchannels_UpdateUsername( _revokeRequestId = request(MTPchannels_UpdateUsername(
pressed->asChannel()->inputChannel, pressed->asChannel()->inputChannel,
MTP_string("") MTP_string()
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {
const auto callback = _revokeCallback; const auto callback = _revokeCallback;
if (_weakRevokeConfirmBox) { if (_weakRevokeConfirmBox) {

View file

@ -167,22 +167,24 @@ void ChangePhoneBox::EnterPhone::sendPhoneDone(const QString &phoneNumber, const
auto codeLength = 0; auto codeLength = 0;
auto &data = result.c_auth_sentCode(); auto &data = result.c_auth_sentCode();
switch (data.vtype.type()) { switch (data.vtype().type()) {
case mtpc_auth_sentCodeTypeApp: case mtpc_auth_sentCodeTypeApp:
LOG(("Error: should not be in-app code!")); LOG(("Error: should not be in-app code!"));
showError(Lang::Hard::ServerError()); showError(Lang::Hard::ServerError());
return; return;
case mtpc_auth_sentCodeTypeSms: codeLength = data.vtype.c_auth_sentCodeTypeSms().vlength.v; break; case mtpc_auth_sentCodeTypeSms: codeLength = data.vtype().c_auth_sentCodeTypeSms().vlength().v; break;
case mtpc_auth_sentCodeTypeCall: codeLength = data.vtype.c_auth_sentCodeTypeCall().vlength.v; break; case mtpc_auth_sentCodeTypeCall: codeLength = data.vtype().c_auth_sentCodeTypeCall().vlength().v; break;
case mtpc_auth_sentCodeTypeFlashCall: case mtpc_auth_sentCodeTypeFlashCall:
LOG(("Error: should not be flashcall!")); LOG(("Error: should not be flashcall!"));
showError(Lang::Hard::ServerError()); showError(Lang::Hard::ServerError());
return; return;
} }
auto phoneCodeHash = qs(data.vphone_code_hash); auto phoneCodeHash = qs(data.vphone_code_hash());
auto callTimeout = 0; auto callTimeout = 0;
if (data.has_next_type() && data.vnext_type.type() == mtpc_auth_codeTypeCall) { if (const auto nextType = data.vnext_type()) {
callTimeout = data.has_timeout() ? data.vtimeout.v : 60; if (nextType->type() == mtpc_auth_codeTypeCall) {
callTimeout = data.vtimeout().value_or(60);
}
} }
Ui::show( Ui::show(
Box<EnterCode>( Box<EnterCode>(

View file

@ -792,8 +792,8 @@ ConfirmInviteBox::ConfirmInviteBox(
, _status(this, st::confirmInviteStatus) , _status(this, st::confirmInviteStatus)
, _participants(GetParticipants(data)) , _participants(GetParticipants(data))
, _isChannel(data.is_channel() && !data.is_megagroup()) { , _isChannel(data.is_channel() && !data.is_megagroup()) {
const auto title = qs(data.vtitle); const auto title = qs(data.vtitle());
const auto count = data.vparticipants_count.v; const auto count = data.vparticipants_count().v;
const auto status = [&] { const auto status = [&] {
return (!_participants.empty() && _participants.size() < count) return (!_participants.empty() && _participants.size() < count)
? tr::lng_group_invite_members(tr::now, lt_count, count) ? tr::lng_group_invite_members(tr::now, lt_count, count)
@ -806,7 +806,7 @@ ConfirmInviteBox::ConfirmInviteBox(
_title->setText(title); _title->setText(title);
_status->setText(status); _status->setText(status);
const auto photo = Auth().data().processPhoto(data.vphoto); const auto photo = Auth().data().processPhoto(data.vphoto());
if (!photo->isNull()) { if (!photo->isNull()) {
_photo = photo->thumbnail(); _photo = photo->thumbnail();
if (!_photo->loaded()) { if (!_photo->loaded()) {
@ -824,10 +824,11 @@ ConfirmInviteBox::ConfirmInviteBox(
std::vector<not_null<UserData*>> ConfirmInviteBox::GetParticipants( std::vector<not_null<UserData*>> ConfirmInviteBox::GetParticipants(
const MTPDchatInvite &data) { const MTPDchatInvite &data) {
if (!data.has_participants()) { const auto participants = data.vparticipants();
if (!participants) {
return {}; return {};
} }
const auto &v = data.vparticipants.v; const auto &v = participants->v;
auto result = std::vector<not_null<UserData*>>(); auto result = std::vector<not_null<UserData*>>();
result.reserve(v.size()); result.reserve(v.size());
for (const auto &participant : v) { for (const auto &participant : v) {

View file

@ -227,21 +227,27 @@ void ConfirmPhoneBox::checkPhoneAndHash() {
} }
void ConfirmPhoneBox::sendCodeDone(const MTPauth_SentCode &result) { void ConfirmPhoneBox::sendCodeDone(const MTPauth_SentCode &result) {
Expects(result.type() == mtpc_auth_sentCode); result.match([&](const MTPDauth_sentCode &data) {
_sendCodeRequestId = 0; _sendCodeRequestId = 0;
_sentCodeLength = data.vtype().match([&](const MTPDauth_sentCodeTypeApp &data) {
auto &resultInner = result.c_auth_sentCode(); LOG(("Error: should not be in-app code!"));
switch (resultInner.vtype.type()) { return 0;
case mtpc_auth_sentCodeTypeApp: LOG(("Error: should not be in-app code!")); break; }, [&](const MTPDauth_sentCodeTypeSms &data) {
case mtpc_auth_sentCodeTypeSms: _sentCodeLength = resultInner.vtype.c_auth_sentCodeTypeSms().vlength.v; break; return data.vlength().v;
case mtpc_auth_sentCodeTypeCall: _sentCodeLength = resultInner.vtype.c_auth_sentCodeTypeCall().vlength.v; break; }, [&](const MTPDauth_sentCodeTypeCall &data) {
case mtpc_auth_sentCodeTypeFlashCall: LOG(("Error: should not be flashcall!")); break; return data.vlength().v;
} }, [&](const MTPDauth_sentCodeTypeFlashCall &data) {
_phoneHash = qs(resultInner.vphone_code_hash); LOG(("Error: should not be flashcall!"));
if (resultInner.has_next_type() && resultInner.vnext_type.type() == mtpc_auth_codeTypeCall) { return 0;
_call.setStatus({ SentCodeCall::State::Waiting, resultInner.has_timeout() ? resultInner.vtimeout.v : 60 }); });
} _phoneHash = qs(data.vphone_code_hash());
launch(); if (const auto nextType = data.vnext_type()) {
if (nextType->type() == mtpc_auth_codeTypeCall) {
_call.setStatus({ SentCodeCall::State::Waiting, data.vtimeout().value_or(60) });
}
}
launch();
});
} }
bool ConfirmPhoneBox::sendCodeFail(const RPCError &error) { bool ConfirmPhoneBox::sendCodeFail(const RPCError &error) {

View file

@ -631,7 +631,7 @@ void PasscodeBox::sendClearCloudPassword(
MTP_account_passwordInputSettings( MTP_account_passwordInputSettings(
MTP_flags(flags), MTP_flags(flags),
Core::PrepareCloudPasswordAlgo(_cloudFields.newAlgo), Core::PrepareCloudPasswordAlgo(_cloudFields.newAlgo),
MTP_bytes(QByteArray()), // new_password_hash MTP_bytes(), // new_password_hash
MTP_string(hint), MTP_string(hint),
MTP_string(email), MTP_string(email),
MTPSecureSecretSettings()) MTPSecureSecretSettings())
@ -693,26 +693,26 @@ void PasscodeBox::changeCloudPassword(
Expects(result.type() == mtpc_account_passwordSettings); Expects(result.type() == mtpc_account_passwordSettings);
const auto &data = result.c_account_passwordSettings(); const auto &data = result.c_account_passwordSettings();
if (!data.has_secure_settings()) { const auto wrapped = data.vsecure_settings();
if (!wrapped) {
checkPasswordHash([=](const Core::CloudPasswordResult &check) { checkPasswordHash([=](const Core::CloudPasswordResult &check) {
const auto empty = QByteArray(); const auto empty = QByteArray();
sendChangeCloudPassword(check, newPassword, empty); sendChangeCloudPassword(check, newPassword, empty);
}); });
return; return;
} }
const auto &wrapped = data.vsecure_settings; const auto &settings = wrapped->c_secureSecretSettings();
const auto &settings = wrapped.c_secureSecretSettings();
const auto passwordUtf = oldPassword.toUtf8(); const auto passwordUtf = oldPassword.toUtf8();
const auto secret = Passport::DecryptSecureSecret( const auto secret = Passport::DecryptSecureSecret(
bytes::make_span(settings.vsecure_secret.v), bytes::make_span(settings.vsecure_secret().v),
Core::ComputeSecureSecretHash( Core::ComputeSecureSecretHash(
Core::ParseSecureSecretAlgo(settings.vsecure_algo), Core::ParseSecureSecretAlgo(settings.vsecure_algo()),
bytes::make_span(passwordUtf))); bytes::make_span(passwordUtf)));
if (secret.empty()) { if (secret.empty()) {
LOG(("API Error: Failed to decrypt secure secret.")); LOG(("API Error: Failed to decrypt secure secret."));
suggestSecretReset(newPassword); suggestSecretReset(newPassword);
} else if (Passport::CountSecureSecretId(secret) } else if (Passport::CountSecureSecretId(secret)
!= settings.vsecure_secret_id.v) { != settings.vsecure_secret_id().v) {
LOG(("API Error: Wrong secure secret id.")); LOG(("API Error: Wrong secure secret id."));
suggestSecretReset(newPassword); suggestSecretReset(newPassword);
} else { } else {
@ -760,7 +760,7 @@ void PasscodeBox::resetSecret(
MTPstring(), // email MTPstring(), // email
MTP_secureSecretSettings( MTP_secureSecretSettings(
MTP_securePasswordKdfAlgoUnknown(), // secure_algo MTP_securePasswordKdfAlgoUnknown(), // secure_algo
MTP_bytes(QByteArray()), // secure_secret MTP_bytes(), // secure_secret
MTP_long(0))) // secure_secret_id MTP_long(0))) // secure_secret_id
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {
_setRequest = 0; _setRequest = 0;
@ -899,7 +899,7 @@ void PasscodeBox::recover() {
} }
void PasscodeBox::recoverStarted(const MTPauth_PasswordRecovery &result) { void PasscodeBox::recoverStarted(const MTPauth_PasswordRecovery &result) {
_pattern = qs(result.c_auth_passwordRecovery().vemail_pattern); _pattern = qs(result.c_auth_passwordRecovery().vemail_pattern());
recover(); recover();
} }

View file

@ -38,10 +38,10 @@ void ShareBotGame(not_null<UserData*> bot, not_null<PeerData*> chat) {
MTP_inputGameShortName( MTP_inputGameShortName(
bot->inputUser, bot->inputUser,
MTP_string(bot->botInfo->shareGameShortName))), MTP_string(bot->botInfo->shareGameShortName))),
MTP_string(""), MTP_string(),
MTP_long(randomId), MTP_long(randomId),
MTPReplyMarkup(), MTPReplyMarkup(),
MTPnullEntities), MTPVector<MTPMessageEntity>()),
App::main()->rpcDone(&MainWidget::sentUpdatesReceived), App::main()->rpcDone(&MainWidget::sentUpdatesReceived),
App::main()->rpcFail(&MainWidget::sendMessageFail), App::main()->rpcFail(&MainWidget::sendMessageFail),
0, 0,
@ -182,8 +182,8 @@ void PeerListGlobalSearchController::searchDone(
auto &contacts = result.c_contacts_found(); auto &contacts = result.c_contacts_found();
auto query = _query; auto query = _query;
if (requestId) { if (requestId) {
Auth().data().processUsers(contacts.vusers); Auth().data().processUsers(contacts.vusers());
Auth().data().processChats(contacts.vchats); Auth().data().processChats(contacts.vchats());
auto it = _queries.find(requestId); auto it = _queries.find(requestId);
if (it != _queries.cend()) { if (it != _queries.cend()) {
query = it->second; query = it->second;
@ -200,8 +200,8 @@ void PeerListGlobalSearchController::searchDone(
}; };
if (_requestId == requestId) { if (_requestId == requestId) {
_requestId = 0; _requestId = 0;
feedList(contacts.vmy_results); feedList(contacts.vmy_results());
feedList(contacts.vresults); feedList(contacts.vresults());
delegate()->peerListSearchRefreshRows(); delegate()->peerListSearchRefreshRows();
} }
} }

View file

@ -444,8 +444,8 @@ bool AddSpecialBoxController::checkInfoLoaded(
Expects(result.type() == mtpc_channels_channelParticipant); Expects(result.type() == mtpc_channels_channelParticipant);
const auto &participant = result.c_channels_channelParticipant(); const auto &participant = result.c_channels_channelParticipant();
channel->owner().processUsers(participant.vusers); channel->owner().processUsers(participant.vusers());
_additional.applyParticipant(participant.vparticipant); _additional.applyParticipant(participant.vparticipant());
callback(); callback();
}).fail([=](const RPCError &error) { }).fail([=](const RPCError &error) {
_additional.setExternal(user); _additional.setExternal(user);
@ -576,7 +576,7 @@ void AddSpecialBoxController::editAdminDone(
} }
const auto date = unixtime(); // Incorrect, but ignored. const auto date = unixtime(); // Incorrect, but ignored.
if (rights.c_chatAdminRights().vflags.v == 0) { if (rights.c_chatAdminRights().vflags().v == 0) {
_additional.applyParticipant(MTP_channelParticipant( _additional.applyParticipant(MTP_channelParticipant(
MTP_int(user->bareId()), MTP_int(user->bareId()),
MTP_int(date))); MTP_int(date)));
@ -673,7 +673,7 @@ void AddSpecialBoxController::editRestrictedDone(
} }
const auto date = unixtime(); // Incorrect, but ignored. const auto date = unixtime(); // Incorrect, but ignored.
if (rights.c_chatBannedRights().vflags.v == 0) { if (rights.c_chatBannedRights().vflags().v == 0) {
_additional.applyParticipant(MTP_channelParticipant( _additional.applyParticipant(MTP_channelParticipant(
MTP_int(user->bareId()), MTP_int(user->bareId()),
MTP_int(date))); MTP_int(date)));
@ -938,7 +938,7 @@ void AddSpecialBoxSearchController::searchParticipantsDone(
} }
_requestId = 0; _requestId = 0;
result.match([&](const MTPDchannels_channelParticipants &data) { result.match([&](const MTPDchannels_channelParticipants &data) {
const auto &list = data.vparticipants.v; const auto &list = data.vparticipants().v;
if (list.size() < requestedCount) { if (list.size() < requestedCount) {
// We want cache to have full information about a query with // We want cache to have full information about a query with
// small results count (that we don't need the second request). // small results count (that we don't need the second request).
@ -992,8 +992,8 @@ void AddSpecialBoxSearchController::searchGlobalDone(
auto &found = result.c_contacts_found(); auto &found = result.c_contacts_found();
auto query = _query; auto query = _query;
if (requestId) { if (requestId) {
_peer->owner().processUsers(found.vusers); _peer->owner().processUsers(found.vusers());
_peer->owner().processChats(found.vchats); _peer->owner().processChats(found.vchats());
auto it = _globalQueries.find(requestId); auto it = _globalQueries.find(requestId);
if (it != _globalQueries.cend()) { if (it != _globalQueries.cend()) {
query = it->second; query = it->second;
@ -1016,8 +1016,8 @@ void AddSpecialBoxSearchController::searchGlobalDone(
if (_requestId == requestId) { if (_requestId == requestId) {
_requestId = 0; _requestId = 0;
_globalLoaded = true; _globalLoaded = true;
feedList(found.vmy_results); feedList(found.vmy_results());
feedList(found.vresults); feedList(found.vresults());
delegate()->peerListSearchRefreshRows(); delegate()->peerListSearchRefreshRows();
} }
} }

View file

@ -251,7 +251,7 @@ EditAdminBox::EditAdminBox(
nullptr, nullptr,
peer, peer,
user, user,
(rights.c_chatAdminRights().vflags.v != 0)) (rights.c_chatAdminRights().vflags().v != 0))
, _oldRights(rights) { , _oldRights(rights) {
} }
@ -277,7 +277,7 @@ void EditAdminBox::prepare() {
EditParticipantBox::prepare(); EditParticipantBox::prepare();
auto hadRights = _oldRights.c_chatAdminRights().vflags.v; auto hadRights = _oldRights.c_chatAdminRights().vflags().v;
setTitle(hadRights setTitle(hadRights
? tr::lng_rights_edit_admin() ? tr::lng_rights_edit_admin()
: tr::lng_channel_add_admin()); : tr::lng_channel_add_admin());
@ -297,7 +297,7 @@ void EditAdminBox::prepare() {
&& channel && channel
&& !channel->amCreator(); && !channel->amCreator();
const auto prepareFlags = disabledByDefaults const auto prepareFlags = disabledByDefaults
| (prepareRights.c_chatAdminRights().vflags.v | (prepareRights.c_chatAdminRights().vflags().v
& (filterByMyRights ? channel->adminRights() : ~Flag(0))); & (filterByMyRights ? channel->adminRights() : ~Flag(0)));
const auto disabledMessages = [&] { const auto disabledMessages = [&] {
@ -601,11 +601,11 @@ void EditRestrictedBox::prepare() {
const auto defaultRestrictions = chat const auto defaultRestrictions = chat
? chat->defaultRestrictions() ? chat->defaultRestrictions()
: channel->defaultRestrictions(); : channel->defaultRestrictions();
const auto prepareRights = (_oldRights.c_chatBannedRights().vflags.v const auto prepareRights = (_oldRights.c_chatBannedRights().vflags().v
? _oldRights ? _oldRights
: Defaults(peer())); : Defaults(peer()));
const auto prepareFlags = FixDependentRestrictions( const auto prepareFlags = FixDependentRestrictions(
prepareRights.c_chatBannedRights().vflags.v prepareRights.c_chatBannedRights().vflags().v
| defaultRestrictions | defaultRestrictions
| ((channel && channel->isPublic()) | ((channel && channel->isPublic())
? (Flag::f_change_info | Flag::f_pin_messages) ? (Flag::f_change_info | Flag::f_pin_messages)
@ -636,7 +636,7 @@ void EditRestrictedBox::prepare() {
disabledMessages); disabledMessages);
addControl(std::move(checkboxes), QMargins()); addControl(std::move(checkboxes), QMargins());
_until = prepareRights.c_chatBannedRights().vuntil_date.v; _until = prepareRights.c_chatBannedRights().vuntil_date().v;
addControl(object_ptr<BoxContentDivider>(this), st::rightsUntilMargin); addControl(object_ptr<BoxContentDivider>(this), st::rightsUntilMargin);
addControl( addControl(
object_ptr<Ui::FlatLabel>( object_ptr<Ui::FlatLabel>(
@ -755,7 +755,7 @@ void EditRestrictedBox::createUntilVariants() {
} }
}; };
auto addCurrentVariant = [&](TimeId from, TimeId to) { auto addCurrentVariant = [&](TimeId from, TimeId to) {
auto oldUntil = _oldRights.c_chatBannedRights().vuntil_date.v; auto oldUntil = _oldRights.c_chatBannedRights().vuntil_date().v;
if (oldUntil < _until) { if (oldUntil < _until) {
addCustomVariant(oldUntil, from, to); addCustomVariant(oldUntil, from, to);
} }

View file

@ -210,7 +210,7 @@ Fn<void(
}; };
const auto flags = newRights.match([]( const auto flags = newRights.match([](
const MTPDchatAdminRights &data) { const MTPDchatAdminRights &data) {
return data.vflags.v; return data.vflags().v;
}); });
if (flags == ChatData::DefaultAdminRights()) { if (flags == ChatData::DefaultAdminRights()) {
saveChatAdmin(true); saveChatAdmin(true);
@ -250,7 +250,7 @@ Fn<void(
if (const auto chat = peer->asChatNotMigrated()) { if (const auto chat = peer->asChatNotMigrated()) {
const auto flags = newRights.match([]( const auto flags = newRights.match([](
const MTPDchatBannedRights &data) { const MTPDchatBannedRights &data) {
return data.vflags.v; return data.vflags().v;
}); });
if (flags & MTPDchatBannedRights::Flag::f_view_messages) { if (flags & MTPDchatBannedRights::Flag::f_view_messages) {
SaveChatParticipantKick(chat, user, done, onFail); SaveChatParticipantKick(chat, user, done, onFail);
@ -510,13 +510,13 @@ UserData *ParticipantsAdditionalData::applyParticipant(
&& overrideRole != Role::Members) { && overrideRole != Role::Members) {
return logBad(); return logBad();
} }
return applyRegular(data.vuser_id); return applyRegular(data.vuser_id());
}, [&](const MTPDchannelParticipant &data) { }, [&](const MTPDchannelParticipant &data) {
if (overrideRole != Role::Profile if (overrideRole != Role::Profile
&& overrideRole != Role::Members) { && overrideRole != Role::Members) {
return logBad(); return logBad();
} }
return applyRegular(data.vuser_id); return applyRegular(data.vuser_id());
}, [&](const MTPDchannelParticipantBanned &data) { }, [&](const MTPDchannelParticipantBanned &data) {
if (overrideRole != Role::Profile if (overrideRole != Role::Profile
&& overrideRole != Role::Members && overrideRole != Role::Members
@ -530,7 +530,7 @@ UserData *ParticipantsAdditionalData::applyParticipant(
UserData *ParticipantsAdditionalData::applyCreator( UserData *ParticipantsAdditionalData::applyCreator(
const MTPDchannelParticipantCreator &data) { const MTPDchannelParticipantCreator &data) {
if (const auto user = applyRegular(data.vuser_id)) { if (const auto user = applyRegular(data.vuser_id())) {
_creator = user; _creator = user;
return user; return user;
} }
@ -539,7 +539,7 @@ UserData *ParticipantsAdditionalData::applyCreator(
UserData *ParticipantsAdditionalData::applyAdmin( UserData *ParticipantsAdditionalData::applyAdmin(
const MTPDchannelParticipantAdmin &data) { const MTPDchannelParticipantAdmin &data) {
const auto user = _peer->owner().userLoaded(data.vuser_id.v); const auto user = _peer->owner().userLoaded(data.vuser_id().v);
if (!user) { if (!user) {
return nullptr; return nullptr;
} else if (const auto chat = _peer->asChat()) { } else if (const auto chat = _peer->asChat()) {
@ -552,13 +552,13 @@ UserData *ParticipantsAdditionalData::applyAdmin(
_restrictedRights.erase(user); _restrictedRights.erase(user);
_kicked.erase(user); _kicked.erase(user);
_restrictedBy.erase(user); _restrictedBy.erase(user);
_adminRights[user] = data.vadmin_rights; _adminRights[user] = data.vadmin_rights();
if (data.is_can_edit()) { if (data.is_can_edit()) {
_adminCanEdit.emplace(user); _adminCanEdit.emplace(user);
} else { } else {
_adminCanEdit.erase(user); _adminCanEdit.erase(user);
} }
if (const auto by = _peer->owner().userLoaded(data.vpromoted_by.v)) { if (const auto by = _peer->owner().userLoaded(data.vpromoted_by().v)) {
const auto i = _adminPromotedBy.find(user); const auto i = _adminPromotedBy.find(user);
if (i == _adminPromotedBy.end()) { if (i == _adminPromotedBy.end()) {
_adminPromotedBy.emplace(user, by); _adminPromotedBy.emplace(user, by);
@ -567,7 +567,7 @@ UserData *ParticipantsAdditionalData::applyAdmin(
} }
} else { } else {
LOG(("API Error: No user %1 for admin promoted by." LOG(("API Error: No user %1 for admin promoted by."
).arg(data.vpromoted_by.v)); ).arg(data.vpromoted_by().v));
} }
return user; return user;
} }
@ -594,7 +594,7 @@ UserData *ParticipantsAdditionalData::applyRegular(MTPint userId) {
UserData *ParticipantsAdditionalData::applyBanned( UserData *ParticipantsAdditionalData::applyBanned(
const MTPDchannelParticipantBanned &data) { const MTPDchannelParticipantBanned &data) {
const auto user = _peer->owner().userLoaded(data.vuser_id.v); const auto user = _peer->owner().userLoaded(data.vuser_id().v);
if (!user) { if (!user) {
return nullptr; return nullptr;
} }
@ -608,8 +608,8 @@ UserData *ParticipantsAdditionalData::applyBanned(
} else { } else {
_kicked.erase(user); _kicked.erase(user);
} }
_restrictedRights[user] = data.vbanned_rights; _restrictedRights[user] = data.vbanned_rights();
if (const auto by = _peer->owner().userLoaded(data.vkicked_by.v)) { if (const auto by = _peer->owner().userLoaded(data.vkicked_by().v)) {
const auto i = _restrictedBy.find(user); const auto i = _restrictedBy.find(user);
if (i == _restrictedBy.end()) { if (i == _restrictedBy.end()) {
_restrictedBy.emplace(user, by); _restrictedBy.emplace(user, by);
@ -1201,9 +1201,9 @@ void ParticipantsBoxController::loadMoreRows() {
} else if (_role == Role::Admins) { } else if (_role == Role::Admins) {
return MTP_channelParticipantsAdmins(); return MTP_channelParticipantsAdmins();
} else if (_role == Role::Restricted) { } else if (_role == Role::Restricted) {
return MTP_channelParticipantsBanned(MTP_string(QString())); return MTP_channelParticipantsBanned(MTP_string());
} }
return MTP_channelParticipantsKicked(MTP_string(QString())); return MTP_channelParticipantsKicked(MTP_string());
}(); }();
// First query is small and fast, next loads a lot of rows. // First query is small and fast, next loads a lot of rows.
@ -1442,7 +1442,7 @@ void ParticipantsBoxController::editAdminDone(
} }
const auto date = unixtime(); // Incorrect, but ignored. const auto date = unixtime(); // Incorrect, but ignored.
if (rights.c_chatAdminRights().vflags.v == 0) { if (rights.c_chatAdminRights().vflags().v == 0) {
_additional.applyParticipant(MTP_channelParticipant( _additional.applyParticipant(MTP_channelParticipant(
MTP_int(user->bareId()), MTP_int(user->bareId()),
MTP_int(date))); MTP_int(date)));
@ -1510,7 +1510,7 @@ void ParticipantsBoxController::editRestrictedDone(
} }
const auto date = unixtime(); // Incorrect, but ignored. const auto date = unixtime(); // Incorrect, but ignored.
if (rights.c_chatBannedRights().vflags.v == 0) { if (rights.c_chatBannedRights().vflags().v == 0) {
_additional.applyParticipant(MTP_channelParticipant( _additional.applyParticipant(MTP_channelParticipant(
MTP_int(user->bareId()), MTP_int(user->bareId()),
MTP_int(date))); MTP_int(date)));
@ -1996,7 +1996,7 @@ void ParticipantsBoxSearchController::searchDone(
_requestId = 0; _requestId = 0;
result.match([&](const MTPDchannels_channelParticipants &data) { result.match([&](const MTPDchannels_channelParticipants &data) {
const auto &list = data.vparticipants.v; const auto &list = data.vparticipants().v;
if (list.size() < requestedCount) { if (list.size() < requestedCount) {
// We want cache to have full information about a query with // We want cache to have full information about a query with
// small results count (that we don't need the second request). // small results count (that we don't need the second request).

View file

@ -553,7 +553,7 @@ void Controller::showEditLinkedChatBox() {
).done([=](const MTPmessages_Chats &result) { ).done([=](const MTPmessages_Chats &result) {
_linkedChatsRequestId = 0; _linkedChatsRequestId = 0;
const auto list = result.match([&](const auto &data) { const auto list = result.match([&](const auto &data) {
return data.vchats.v; return data.vchats().v;
}); });
auto chats = std::vector<not_null<PeerData*>>(); auto chats = std::vector<not_null<PeerData*>>();
chats.reserve(list.size()); chats.reserve(list.size());

View file

@ -141,7 +141,7 @@ void SessionsBox::got(const MTPaccount_Authorizations &result) {
_data = Full(); _data = Full();
result.match([&](const MTPDaccount_authorizations &data) { result.match([&](const MTPDaccount_authorizations &data) {
const auto &list = data.vauthorizations.v; const auto &list = data.vauthorizations().v;
for (const auto &auth : list) { for (const auto &auth : list) {
auth.match([&](const MTPDauthorization &data) { auth.match([&](const MTPDauthorization &data) {
auto entry = ParseEntry(data); auto entry = ParseEntry(data);
@ -170,14 +170,14 @@ void SessionsBox::got(const MTPaccount_Authorizations &result) {
SessionsBox::Entry SessionsBox::ParseEntry(const MTPDauthorization &data) { SessionsBox::Entry SessionsBox::ParseEntry(const MTPDauthorization &data) {
auto result = Entry(); auto result = Entry();
result.hash = data.is_current() ? 0 : data.vhash.v; result.hash = data.is_current() ? 0 : data.vhash().v;
result.incomplete = data.is_password_pending(); result.incomplete = data.is_password_pending();
auto appName = QString(); auto appName = QString();
auto appVer = qs(data.vapp_version); auto appVer = qs(data.vapp_version());
const auto systemVer = qs(data.vsystem_version); const auto systemVer = qs(data.vsystem_version());
const auto deviceModel = qs(data.vdevice_model); const auto deviceModel = qs(data.vdevice_model());
const auto apiId = data.vapi_id.v; const auto apiId = data.vapi_id().v;
if (apiId == 2040 || apiId == 17349) { if (apiId == 2040 || apiId == 17349) {
appName = (apiId == 2040) appName = (apiId == 2040)
? qstr("Telegram Desktop") ? qstr("Telegram Desktop")
@ -201,7 +201,7 @@ SessionsBox::Entry SessionsBox::ParseEntry(const MTPDauthorization &data) {
// appVer = QString(); // appVer = QString();
} }
} else { } else {
appName = qs(data.vapp_name);// +qsl(" for ") + qs(d.vplatform); appName = qs(data.vapp_name());// +qsl(" for ") + qs(d.vplatform());
if (appVer.indexOf('(') >= 0) { if (appVer.indexOf('(') >= 0) {
appVer = appVer.mid(appVer.indexOf('(')); appVer = appVer.mid(appVer.indexOf('('));
} }
@ -211,19 +211,19 @@ SessionsBox::Entry SessionsBox::ParseEntry(const MTPDauthorization &data) {
result.name += ' ' + appVer; result.name += ' ' + appVer;
} }
const auto country = qs(data.vcountry); const auto country = qs(data.vcountry());
const auto platform = qs(data.vplatform); const auto platform = qs(data.vplatform());
//const auto &countries = countriesByISO2(); //const auto &countries = countriesByISO2();
//const auto j = countries.constFind(country); //const auto j = countries.constFind(country);
//if (j != countries.cend()) { //if (j != countries.cend()) {
// country = QString::fromUtf8(j.value()->name); // country = QString::fromUtf8(j.value()->name);
//} //}
result.activeTime = data.vdate_active.v result.activeTime = data.vdate_active().v
? data.vdate_active.v ? data.vdate_active().v
: data.vdate_created.v; : data.vdate_created().v;
result.info = qs(data.vdevice_model) + qstr(", ") + (platform.isEmpty() ? QString() : platform + ' ') + qs(data.vsystem_version); result.info = qs(data.vdevice_model()) + qstr(", ") + (platform.isEmpty() ? QString() : platform + ' ') + qs(data.vsystem_version());
result.ip = qs(data.vip) + (country.isEmpty() ? QString() : QString::fromUtf8(" \xe2\x80\x93 ") + country); result.ip = qs(data.vip()) + (country.isEmpty() ? QString() : QString::fromUtf8(" \xe2\x80\x93 ") + country);
if (!result.hash) { if (!result.hash) {
result.active = tr::lng_status_online(tr::now); result.active = tr::lng_status_online(tr::now);
result.activeWidth = st::sessionWhenFont->width(tr::lng_status_online(tr::now)); result.activeWidth = st::sessionWhenFont->width(tr::lng_status_online(tr::now));

View file

@ -336,12 +336,12 @@ void ShareBox::peopleReceived(
switch (result.type()) { switch (result.type()) {
case mtpc_contacts_found: { case mtpc_contacts_found: {
auto &found = result.c_contacts_found(); auto &found = result.c_contacts_found();
Auth().data().processUsers(found.vusers); Auth().data().processUsers(found.vusers());
Auth().data().processChats(found.vchats); Auth().data().processChats(found.vchats());
_inner->peopleReceived( _inner->peopleReceived(
query, query,
found.vmy_results.v, found.vmy_results().v,
found.vresults.v); found.vresults().v);
} break; } break;
} }
@ -1151,7 +1151,7 @@ void ShareGameScoreByHash(const QString &hash) {
auto requestChannel = MTPchannels_GetChannels(requestChannelIds); auto requestChannel = MTPchannels_GetChannels(requestChannelIds);
MTP::send(requestChannel, rpcDone([=](const MTPmessages_Chats &result) { MTP::send(requestChannel, rpcDone([=](const MTPmessages_Chats &result) {
result.match([](const auto &data) { result.match([](const auto &data) {
Auth().data().processChats(data.vchats); Auth().data().processChats(data.vchats());
}); });
if (const auto channel = Auth().data().channelLoaded(channelId)) { if (const auto channel = Auth().data().channelLoaded(channelId)) {
resolveMessageAndShareScore(channel); resolveMessageAndShareScore(channel);

View file

@ -217,10 +217,10 @@ StickerSetBox::Inner::Inner(
, _input(set) , _input(set)
, _previewTimer([=] { showPreview(); }) { , _previewTimer([=] { showPreview(); }) {
set.match([&](const MTPDinputStickerSetID &data) { set.match([&](const MTPDinputStickerSetID &data) {
_setId = data.vid.v; _setId = data.vid().v;
_setAccess = data.vaccess_hash.v; _setAccess = data.vaccess_hash().v;
}, [&](const MTPDinputStickerSetShortName &data) { }, [&](const MTPDinputStickerSetShortName &data) {
_setShortName = qs(data.vshort_name); _setShortName = qs(data.vshort_name());
}, [&](const MTPDinputStickerSetEmpty &) { }, [&](const MTPDinputStickerSetEmpty &) {
}); });
@ -247,7 +247,7 @@ void StickerSetBox::Inner::gotSet(const MTPmessages_StickerSet &set) {
_selected = -1; _selected = -1;
setCursor(style::cur_default); setCursor(style::cur_default);
set.match([&](const MTPDmessages_stickerSet &data) { set.match([&](const MTPDmessages_stickerSet &data) {
const auto &v = data.vdocuments.v; const auto &v = data.vdocuments().v;
_pack.reserve(v.size()); _pack.reserve(v.size());
_elements.reserve(v.size()); _elements.reserve(v.size());
for (const auto &item : v) { for (const auto &item : v) {
@ -259,11 +259,11 @@ void StickerSetBox::Inner::gotSet(const MTPmessages_StickerSet &set) {
_pack.push_back(document); _pack.push_back(document);
_elements.push_back({ document }); _elements.push_back({ document });
} }
for (const auto &pack : data.vpacks.v) { for (const auto &pack : data.vpacks().v) {
pack.match([&](const MTPDstickerPack &pack) { pack.match([&](const MTPDstickerPack &pack) {
if (const auto emoji = Ui::Emoji::Find(qs(pack.vemoticon))) { if (const auto emoji = Ui::Emoji::Find(qs(pack.vemoticon()))) {
const auto original = emoji->original(); const auto original = emoji->original();
auto &stickers = pack.vdocuments.v; auto &stickers = pack.vdocuments().v;
auto p = Stickers::Pack(); auto p = Stickers::Pack();
p.reserve(stickers.size()); p.reserve(stickers.size());
@ -277,20 +277,20 @@ void StickerSetBox::Inner::gotSet(const MTPmessages_StickerSet &set) {
} }
}); });
} }
data.vset.match([&](const MTPDstickerSet &set) { data.vset().match([&](const MTPDstickerSet &set) {
_setTitle = Stickers::GetSetTitle(set); _setTitle = Stickers::GetSetTitle(set);
_setShortName = qs(set.vshort_name); _setShortName = qs(set.vshort_name());
_setId = set.vid.v; _setId = set.vid().v;
_setAccess = set.vaccess_hash.v; _setAccess = set.vaccess_hash().v;
_setCount = set.vcount.v; _setCount = set.vcount().v;
_setHash = set.vhash.v; _setHash = set.vhash().v;
_setFlags = set.vflags.v; _setFlags = set.vflags().v;
_setInstallDate = set.has_installed_date() _setInstallDate = set.vinstalled_date().value_or(0);
? set.vinstalled_date.v if (const auto thumb = set.vthumb()) {
: TimeId(0); _setThumbnail = Images::Create(set, *thumb);
_setThumbnail = set.has_thumb() } else {
? Images::Create(set, set.vthumb) _setThumbnail = ImagePtr();
: ImagePtr(); }
auto &sets = Auth().data().stickerSetsRef(); auto &sets = Auth().data().stickerSetsRef();
const auto it = sets.find(_setId); const auto it = sets.find(_setId);
if (it != sets.cend()) { if (it != sets.cend()) {

View file

@ -158,7 +158,7 @@ void StickersBox::showAttachedStickers() {
auto addedSet = false; auto addedSet = false;
for (const auto &stickerSet : _attachedSets.v) { for (const auto &stickerSet : _attachedSets.v) {
const auto setData = stickerSet.match([&](const auto &data) { const auto setData = stickerSet.match([&](const auto &data) {
return data.vset.match([&](const MTPDstickerSet &data) { return data.vset().match([&](const MTPDstickerSet &data) {
return &data; return &data;
}); });
}); });
@ -201,19 +201,19 @@ void StickersBox::getArchivedDone(uint64 offsetId, const MTPmessages_ArchivedSti
auto addedSet = false; auto addedSet = false;
auto changedSets = false; auto changedSets = false;
for_const (const auto &stickerSet, stickers.vsets.v) { for_const (const auto &stickerSet, stickers.vsets().v) {
const MTPDstickerSet *setData = nullptr; const MTPDstickerSet *setData = nullptr;
switch (stickerSet.type()) { switch (stickerSet.type()) {
case mtpc_stickerSetCovered: { case mtpc_stickerSetCovered: {
auto &d = stickerSet.c_stickerSetCovered(); auto &d = stickerSet.c_stickerSetCovered();
if (d.vset.type() == mtpc_stickerSet) { if (d.vset().type() == mtpc_stickerSet) {
setData = &d.vset.c_stickerSet(); setData = &d.vset().c_stickerSet();
} }
} break; } break;
case mtpc_stickerSetMultiCovered: { case mtpc_stickerSetMultiCovered: {
auto &d = stickerSet.c_stickerSetMultiCovered(); auto &d = stickerSet.c_stickerSetMultiCovered();
if (d.vset.type() == mtpc_stickerSet) { if (d.vset().type() == mtpc_stickerSet) {
setData = &d.vset.c_stickerSet(); setData = &d.vset().c_stickerSet();
} }
} break; } break;
} }
@ -239,7 +239,7 @@ void StickersBox::getArchivedDone(uint64 offsetId, const MTPmessages_ArchivedSti
if (addedSet) { if (addedSet) {
_archived.widget()->updateSize(); _archived.widget()->updateSize();
} else { } else {
_allArchivedLoaded = stickers.vsets.v.isEmpty() _allArchivedLoaded = stickers.vsets().v.isEmpty()
|| (!changedSets && offsetId != 0); || (!changedSets && offsetId != 0);
if (changedSets) { if (changedSets) {
loadMoreArchived(); loadMoreArchived();
@ -1324,8 +1324,8 @@ void StickersBox::Inner::mouseReleaseEvent(QMouseEvent *e) {
void StickersBox::Inner::saveGroupSet() { void StickersBox::Inner::saveGroupSet() {
Expects(_megagroupSet != nullptr); Expects(_megagroupSet != nullptr);
auto oldId = (_megagroupSet->mgInfo->stickerSet.type() == mtpc_inputStickerSetID) ? _megagroupSet->mgInfo->stickerSet.c_inputStickerSetID().vid.v : 0; auto oldId = (_megagroupSet->mgInfo->stickerSet.type() == mtpc_inputStickerSetID) ? _megagroupSet->mgInfo->stickerSet.c_inputStickerSetID().vid().v : 0;
auto newId = (_megagroupSetInput.type() == mtpc_inputStickerSetID) ? _megagroupSetInput.c_inputStickerSetID().vid.v : 0; auto newId = (_megagroupSetInput.type() == mtpc_inputStickerSetID) ? _megagroupSetInput.c_inputStickerSetID().vid().v : 0;
if (newId != oldId) { if (newId != oldId) {
Auth().api().setGroupStickerSet(_megagroupSet, _megagroupSetInput); Auth().api().setGroupStickerSet(_megagroupSet, _megagroupSetInput);
Auth().api().stickerSetInstalled(Stickers::MegagroupSetId); Auth().api().stickerSetInstalled(Stickers::MegagroupSetId);
@ -1492,11 +1492,11 @@ void StickersBox::Inner::rebuildMegagroupSet() {
return; return;
} }
auto &set = _megagroupSetInput.c_inputStickerSetID(); auto &set = _megagroupSetInput.c_inputStickerSetID();
auto setId = set.vid.v; auto setId = set.vid().v;
auto &sets = Auth().data().stickerSets(); auto &sets = Auth().data().stickerSets();
auto it = sets.find(setId); auto it = sets.find(setId);
if (it == sets.cend() || (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) { if (it == sets.cend() || (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) {
Auth().api().scheduleStickerSetRequest(set.vid.v, set.vaccess_hash.v); Auth().api().scheduleStickerSetRequest(set.vid().v, set.vaccess_hash().v);
return; return;
} }

View file

@ -48,7 +48,7 @@ void UrlAuthBox::Activate(
button->requestId = 0; button->requestId = 0;
result.match([&](const MTPDurlAuthResultAccepted &data) { result.match([&](const MTPDurlAuthResultAccepted &data) {
UrlClickHandler::Open(qs(data.vurl)); UrlClickHandler::Open(qs(data.vurl()));
}, [&](const MTPDurlAuthResultDefault &data) { }, [&](const MTPDurlAuthResultDefault &data) {
HiddenUrlClickHandler::Open(url); HiddenUrlClickHandler::Open(url);
}, [&](const MTPDurlAuthResultRequest &data) { }, [&](const MTPDurlAuthResultRequest &data) {
@ -82,7 +82,7 @@ void UrlAuthBox::Request(
const auto url = QString::fromUtf8(button->data); const auto url = QString::fromUtf8(button->data);
const auto bot = request.is_request_write_access() const auto bot = request.is_request_write_access()
? session->data().processUser(request.vbot).get() ? session->data().processUser(request.vbot()).get()
: nullptr; : nullptr;
const auto box = std::make_shared<QPointer<BoxContent>>(); const auto box = std::make_shared<QPointer<BoxContent>>();
const auto finishWithUrl = [=](const QString &url) { const auto finishWithUrl = [=](const QString &url) {
@ -105,7 +105,7 @@ void UrlAuthBox::Request(
)).done([=](const MTPUrlAuthResult &result) { )).done([=](const MTPUrlAuthResult &result) {
const auto to = result.match( const auto to = result.match(
[&](const MTPDurlAuthResultAccepted &data) { [&](const MTPDurlAuthResultAccepted &data) {
return qs(data.vurl); return qs(data.vurl());
}, [&](const MTPDurlAuthResultDefault &data) { }, [&](const MTPDurlAuthResultDefault &data) {
return url; return url;
}, [&](const MTPDurlAuthResultRequest &data) { }, [&](const MTPDurlAuthResultRequest &data) {
@ -120,7 +120,7 @@ void UrlAuthBox::Request(
} }
}; };
*box = Ui::show( *box = Ui::show(
Box<UrlAuthBox>(url, qs(request.vdomain), bot, callback), Box<UrlAuthBox>(url, qs(request.vdomain()), bot, callback),
LayerOption::KeepOther); LayerOption::KeepOther);
} }

View file

@ -246,7 +246,7 @@ void BoxController::loadMoreRows() {
_loadRequestId = request(MTPmessages_Search( _loadRequestId = request(MTPmessages_Search(
MTP_flags(0), MTP_flags(0),
MTP_inputPeerEmpty(), MTP_inputPeerEmpty(),
MTP_string(QString()), MTP_string(),
MTP_inputUserEmpty(), MTP_inputUserEmpty(),
MTP_inputMessagesFilterPhoneCalls(MTP_flags(0)), MTP_inputMessagesFilterPhoneCalls(MTP_flags(0)),
MTP_int(0), MTP_int(0),
@ -261,9 +261,9 @@ void BoxController::loadMoreRows() {
_loadRequestId = 0; _loadRequestId = 0;
auto handleResult = [&](auto &data) { auto handleResult = [&](auto &data) {
Auth().data().processUsers(data.vusers); Auth().data().processUsers(data.vusers());
Auth().data().processChats(data.vchats); Auth().data().processChats(data.vchats());
receivedCalls(data.vmessages.v); receivedCalls(data.vmessages().v);
}; };
switch (result.type()) { switch (result.type()) {

View file

@ -45,22 +45,22 @@ void AppendEndpoint(
std::vector<tgvoip::Endpoint> &list, std::vector<tgvoip::Endpoint> &list,
const MTPPhoneConnection &connection) { const MTPPhoneConnection &connection) {
connection.match([&](const MTPDphoneConnection &data) { connection.match([&](const MTPDphoneConnection &data) {
if (data.vpeer_tag.v.length() != 16) { if (data.vpeer_tag().v.length() != 16) {
return; return;
} }
const auto ipv4 = tgvoip::IPv4Address(std::string( const auto ipv4 = tgvoip::IPv4Address(std::string(
data.vip.v.constData(), data.vip().v.constData(),
data.vip.v.size())); data.vip().v.size()));
const auto ipv6 = tgvoip::IPv6Address(std::string( const auto ipv6 = tgvoip::IPv6Address(std::string(
data.vipv6.v.constData(), data.vipv6().v.constData(),
data.vipv6.v.size())); data.vipv6().v.size()));
list.emplace_back( list.emplace_back(
(int64_t)data.vid.v, (int64_t)data.vid().v,
(uint16_t)data.vport.v, (uint16_t)data.vport().v,
ipv4, ipv4,
ipv6, ipv6,
tgvoip::Endpoint::Type::UDP_RELAY, tgvoip::Endpoint::Type::UDP_RELAY,
(unsigned char*)data.vpeer_tag.v.data()); (unsigned char*)data.vpeer_tag().v.data());
}); });
} }
@ -204,17 +204,17 @@ void Call::startOutgoing() {
setState(State::Waiting); setState(State::Waiting);
auto &call = result.c_phone_phoneCall(); auto &call = result.c_phone_phoneCall();
Auth().data().processUsers(call.vusers); Auth().data().processUsers(call.vusers());
if (call.vphone_call.type() != mtpc_phoneCallWaiting) { if (call.vphone_call().type() != mtpc_phoneCallWaiting) {
LOG(("Call Error: Expected phoneCallWaiting in response to phone.requestCall()")); LOG(("Call Error: Expected phoneCallWaiting in response to phone.requestCall()"));
finish(FinishType::Failed); finish(FinishType::Failed);
return; return;
} }
auto &phoneCall = call.vphone_call; auto &phoneCall = call.vphone_call();
auto &waitingCall = phoneCall.c_phoneCallWaiting(); auto &waitingCall = phoneCall.c_phoneCallWaiting();
_id = waitingCall.vid.v; _id = waitingCall.vid().v;
_accessHash = waitingCall.vaccess_hash.v; _accessHash = waitingCall.vaccess_hash().v;
if (_finishAfterRequestingCall != FinishType::None) { if (_finishAfterRequestingCall != FinishType::None) {
if (_finishAfterRequestingCall == FinishType::Failed) { if (_finishAfterRequestingCall == FinishType::Failed) {
finish(_finishAfterRequestingCall); finish(_finishAfterRequestingCall);
@ -277,15 +277,15 @@ void Call::actuallyAnswer() {
)).done([=](const MTPphone_PhoneCall &result) { )).done([=](const MTPphone_PhoneCall &result) {
Expects(result.type() == mtpc_phone_phoneCall); Expects(result.type() == mtpc_phone_phoneCall);
auto &call = result.c_phone_phoneCall(); auto &call = result.c_phone_phoneCall();
Auth().data().processUsers(call.vusers); Auth().data().processUsers(call.vusers());
if (call.vphone_call.type() != mtpc_phoneCallWaiting) { if (call.vphone_call().type() != mtpc_phoneCallWaiting) {
LOG(("Call Error: " LOG(("Call Error: "
"Not phoneCallWaiting in response to phone.acceptCall.")); "Not phoneCallWaiting in response to phone.acceptCall."));
finish(FinishType::Failed); finish(FinishType::Failed);
return; return;
} }
handleUpdate(call.vphone_call); handleUpdate(call.vphone_call());
}).fail([=](const RPCError &error) { }).fail([=](const RPCError &error) {
handleRequestError(error); handleRequestError(error);
}).send(); }).send();
@ -371,19 +371,19 @@ bool Call::handleUpdate(const MTPPhoneCall &call) {
auto &data = call.c_phoneCallRequested(); auto &data = call.c_phoneCallRequested();
if (_type != Type::Incoming if (_type != Type::Incoming
|| _id != 0 || _id != 0
|| peerToUser(_user->id) != data.vadmin_id.v) { || peerToUser(_user->id) != data.vadmin_id().v) {
Unexpected("phoneCallRequested call inside an existing call handleUpdate()"); Unexpected("phoneCallRequested call inside an existing call handleUpdate()");
} }
if (Auth().userId() != data.vparticipant_id.v) { if (Auth().userId() != data.vparticipant_id().v) {
LOG(("Call Error: Wrong call participant_id %1, expected %2." LOG(("Call Error: Wrong call participant_id %1, expected %2."
).arg(data.vparticipant_id.v ).arg(data.vparticipant_id().v
).arg(Auth().userId())); ).arg(Auth().userId()));
finish(FinishType::Failed); finish(FinishType::Failed);
return true; return true;
} }
_id = data.vid.v; _id = data.vid().v;
_accessHash = data.vaccess_hash.v; _accessHash = data.vaccess_hash().v;
auto gaHashBytes = bytes::make_span(data.vg_a_hash.v); auto gaHashBytes = bytes::make_span(data.vg_a_hash().v);
if (gaHashBytes.size() != kSha256Size) { if (gaHashBytes.size() != kSha256Size) {
LOG(("Call Error: Wrong g_a_hash size %1, expected %2." LOG(("Call Error: Wrong g_a_hash size %1, expected %2."
).arg(gaHashBytes.size() ).arg(gaHashBytes.size()
@ -396,7 +396,7 @@ bool Call::handleUpdate(const MTPPhoneCall &call) {
case mtpc_phoneCallEmpty: { case mtpc_phoneCallEmpty: {
auto &data = call.c_phoneCallEmpty(); auto &data = call.c_phoneCallEmpty();
if (data.vid.v != _id) { if (data.vid().v != _id) {
return false; return false;
} }
LOG(("Call Error: phoneCallEmpty received.")); LOG(("Call Error: phoneCallEmpty received."));
@ -405,12 +405,12 @@ bool Call::handleUpdate(const MTPPhoneCall &call) {
case mtpc_phoneCallWaiting: { case mtpc_phoneCallWaiting: {
auto &data = call.c_phoneCallWaiting(); auto &data = call.c_phoneCallWaiting();
if (data.vid.v != _id) { if (data.vid().v != _id) {
return false; return false;
} }
if (_type == Type::Outgoing if (_type == Type::Outgoing
&& _state == State::Waiting && _state == State::Waiting
&& data.vreceive_date.v != 0) { && data.vreceive_date().value_or_empty() != 0) {
_discardByTimeoutTimer.callOnce(Global::CallRingTimeoutMs()); _discardByTimeoutTimer.callOnce(Global::CallRingTimeoutMs());
setState(State::Ringing); setState(State::Ringing);
startWaitingTrack(); startWaitingTrack();
@ -419,7 +419,7 @@ bool Call::handleUpdate(const MTPPhoneCall &call) {
case mtpc_phoneCall: { case mtpc_phoneCall: {
auto &data = call.c_phoneCall(); auto &data = call.c_phoneCall();
if (data.vid.v != _id) { if (data.vid().v != _id) {
return false; return false;
} }
if (_type == Type::Incoming if (_type == Type::Incoming
@ -431,7 +431,7 @@ bool Call::handleUpdate(const MTPPhoneCall &call) {
case mtpc_phoneCallDiscarded: { case mtpc_phoneCallDiscarded: {
auto &data = call.c_phoneCallDiscarded(); auto &data = call.c_phoneCallDiscarded();
if (data.vid.v != _id) { if (data.vid().v != _id) {
return false; return false;
} }
if (data.is_need_debug()) { if (data.is_need_debug()) {
@ -448,12 +448,11 @@ bool Call::handleUpdate(const MTPPhoneCall &call) {
if (data.is_need_rating() && _id && _accessHash) { if (data.is_need_rating() && _id && _accessHash) {
Ui::show(Box<RateCallBox>(_id, _accessHash)); Ui::show(Box<RateCallBox>(_id, _accessHash));
} }
if (data.has_reason() const auto reason = data.vreason();
&& data.vreason.type() == mtpc_phoneCallDiscardReasonDisconnect) { if (reason && reason->type() == mtpc_phoneCallDiscardReasonDisconnect) {
LOG(("Call Info: Discarded with DISCONNECT reason.")); LOG(("Call Info: Discarded with DISCONNECT reason."));
} }
if (data.has_reason() if (reason && reason->type() == mtpc_phoneCallDiscardReasonBusy) {
&& data.vreason.type() == mtpc_phoneCallDiscardReasonBusy) {
setState(State::Busy); setState(State::Busy);
} else if (_type == Type::Outgoing || _state == State::HangingUp) { } else if (_type == Type::Outgoing || _state == State::HangingUp) {
setState(State::Ended); setState(State::Ended);
@ -464,7 +463,7 @@ bool Call::handleUpdate(const MTPPhoneCall &call) {
case mtpc_phoneCallAccepted: { case mtpc_phoneCallAccepted: {
auto &data = call.c_phoneCallAccepted(); auto &data = call.c_phoneCallAccepted();
if (data.vid.v != _id) { if (data.vid().v != _id) {
return false; return false;
} }
if (_type != Type::Outgoing) { if (_type != Type::Outgoing) {
@ -489,7 +488,7 @@ void Call::confirmAcceptedCall(const MTPDphoneCallAccepted &call) {
return; return;
} }
const auto firstBytes = bytes::make_span(call.vg_b.v); const auto firstBytes = bytes::make_span(call.vg_b().v);
const auto computedAuthKey = MTP::CreateAuthKey( const auto computedAuthKey = MTP::CreateAuthKey(
firstBytes, firstBytes,
_randomPower, _randomPower,
@ -517,14 +516,14 @@ void Call::confirmAcceptedCall(const MTPDphoneCallAccepted &call) {
Expects(result.type() == mtpc_phone_phoneCall); Expects(result.type() == mtpc_phone_phoneCall);
auto &call = result.c_phone_phoneCall(); auto &call = result.c_phone_phoneCall();
Auth().data().processUsers(call.vusers); Auth().data().processUsers(call.vusers());
if (call.vphone_call.type() != mtpc_phoneCall) { if (call.vphone_call().type() != mtpc_phoneCall) {
LOG(("Call Error: Expected phoneCall in response to phone.confirmCall()")); LOG(("Call Error: Expected phoneCall in response to phone.confirmCall()"));
finish(FinishType::Failed); finish(FinishType::Failed);
return; return;
} }
createAndStartController(call.vphone_call.c_phoneCall()); createAndStartController(call.vphone_call().c_phoneCall());
}).fail([this](const RPCError &error) { }).fail([this](const RPCError &error) {
handleRequestError(error); handleRequestError(error);
}).send(); }).send();
@ -533,7 +532,7 @@ void Call::confirmAcceptedCall(const MTPDphoneCallAccepted &call) {
void Call::startConfirmedCall(const MTPDphoneCall &call) { void Call::startConfirmedCall(const MTPDphoneCall &call) {
Expects(_type == Type::Incoming); Expects(_type == Type::Incoming);
auto firstBytes = bytes::make_span(call.vg_a_or_b.v); auto firstBytes = bytes::make_span(call.vg_a_or_b().v);
if (_gaHash != openssl::Sha256(firstBytes)) { if (_gaHash != openssl::Sha256(firstBytes)) {
LOG(("Call Error: Wrong g_a hash received.")); LOG(("Call Error: Wrong g_a hash received."));
finish(FinishType::Failed); finish(FinishType::Failed);
@ -583,9 +582,9 @@ void Call::createAndStartController(const MTPDphoneCall &call) {
QDir().mkpath(callLogFolder); QDir().mkpath(callLogFolder);
} }
const auto &protocol = call.vprotocol.c_phoneCallProtocol(); const auto &protocol = call.vprotocol().c_phoneCallProtocol();
auto endpoints = std::vector<tgvoip::Endpoint>(); auto endpoints = std::vector<tgvoip::Endpoint>();
for (const auto &connection : call.vconnections.v) { for (const auto &connection : call.vconnections().v) {
AppendEndpoint(endpoints, connection); AppendEndpoint(endpoints, connection);
} }
@ -611,7 +610,7 @@ void Call::createAndStartController(const MTPDphoneCall &call) {
_controller->SetRemoteEndpoints( _controller->SetRemoteEndpoints(
endpoints, endpoints,
call.is_p2p_allowed(), call.is_p2p_allowed(),
protocol.vmax_layer.v); protocol.vmax_layer().v);
_controller->SetConfig(config); _controller->SetConfig(config);
_controller->SetCurrentAudioOutput(Global::CallOutputDeviceID().toStdString()); _controller->SetCurrentAudioOutput(Global::CallOutputDeviceID().toStdString());
_controller->SetCurrentAudioInput(Global::CallInputDeviceID().toStdString()); _controller->SetCurrentAudioInput(Global::CallInputDeviceID().toStdString());
@ -699,18 +698,18 @@ bool Call::checkCallCommonFields(const T &call) {
finish(FinishType::Failed); finish(FinishType::Failed);
return false; return false;
}; };
if (call.vaccess_hash.v != _accessHash) { if (call.vaccess_hash().v != _accessHash) {
LOG(("Call Error: Wrong call access_hash.")); LOG(("Call Error: Wrong call access_hash."));
return checkFailed(); return checkFailed();
} }
auto adminId = (_type == Type::Outgoing) ? Auth().userId() : peerToUser(_user->id); auto adminId = (_type == Type::Outgoing) ? Auth().userId() : peerToUser(_user->id);
auto participantId = (_type == Type::Outgoing) ? peerToUser(_user->id) : Auth().userId(); auto participantId = (_type == Type::Outgoing) ? peerToUser(_user->id) : Auth().userId();
if (call.vadmin_id.v != adminId) { if (call.vadmin_id().v != adminId) {
LOG(("Call Error: Wrong call admin_id %1, expected %2.").arg(call.vadmin_id.v).arg(adminId)); LOG(("Call Error: Wrong call admin_id %1, expected %2.").arg(call.vadmin_id().v).arg(adminId));
return checkFailed(); return checkFailed();
} }
if (call.vparticipant_id.v != participantId) { if (call.vparticipant_id().v != participantId) {
LOG(("Call Error: Wrong call participant_id %1, expected %2.").arg(call.vparticipant_id.v).arg(participantId)); LOG(("Call Error: Wrong call participant_id %1, expected %2.").arg(call.vparticipant_id().v).arg(participantId));
return checkFailed(); return checkFailed();
} }
return true; return true;
@ -720,7 +719,7 @@ bool Call::checkCallFields(const MTPDphoneCall &call) {
if (!checkCallCommonFields(call)) { if (!checkCallCommonFields(call)) {
return false; return false;
} }
if (call.vkey_fingerprint.v != _keyFingerprint) { if (call.vkey_fingerprint().v != _keyFingerprint) {
LOG(("Call Error: Wrong call fingerprint.")); LOG(("Call Error: Wrong call fingerprint."));
finish(FinishType::Failed); finish(FinishType::Failed);
return false; return false;

View file

@ -169,26 +169,26 @@ bytes::const_span Instance::updateDhConfig(
}; };
return data.match([&](const MTPDmessages_dhConfig &data) return data.match([&](const MTPDmessages_dhConfig &data)
-> bytes::const_span { -> bytes::const_span {
auto primeBytes = bytes::make_vector(data.vp.v); auto primeBytes = bytes::make_vector(data.vp().v);
if (!MTP::IsPrimeAndGood(primeBytes, data.vg.v)) { if (!MTP::IsPrimeAndGood(primeBytes, data.vg().v)) {
LOG(("API Error: bad p/g received in dhConfig.")); LOG(("API Error: bad p/g received in dhConfig."));
return {}; return {};
} else if (!validRandom(data.vrandom.v)) { } else if (!validRandom(data.vrandom().v)) {
return {}; return {};
} }
_dhConfig.g = data.vg.v; _dhConfig.g = data.vg().v;
_dhConfig.p = std::move(primeBytes); _dhConfig.p = std::move(primeBytes);
_dhConfig.version = data.vversion.v; _dhConfig.version = data.vversion().v;
return bytes::make_span(data.vrandom.v); return bytes::make_span(data.vrandom().v);
}, [&](const MTPDmessages_dhConfigNotModified &data) }, [&](const MTPDmessages_dhConfigNotModified &data)
-> bytes::const_span { -> bytes::const_span {
if (!_dhConfig.g || _dhConfig.p.empty()) { if (!_dhConfig.g || _dhConfig.p.empty()) {
LOG(("API Error: dhConfigNotModified on zero version.")); LOG(("API Error: dhConfigNotModified on zero version."));
return {}; return {};
} else if (!validRandom(data.vrandom.v)) { } else if (!validRandom(data.vrandom().v)) {
return {}; return {};
} }
return bytes::make_span(data.vrandom.v); return bytes::make_span(data.vrandom().v);
}); });
} }
@ -203,7 +203,7 @@ void Instance::refreshServerConfig() {
_serverConfigRequestId = 0; _serverConfigRequestId = 0;
_lastServerConfigUpdateTime = crl::now(); _lastServerConfigUpdateTime = crl::now();
const auto &json = result.c_dataJSON().vdata.v; const auto &json = result.c_dataJSON().vdata().v;
UpdateConfig(std::string(json.data(), json.size())); UpdateConfig(std::string(json.data(), json.size()));
}).fail([this](const RPCError &error) { }).fail([this](const RPCError &error) {
_serverConfigRequestId = 0; _serverConfigRequestId = 0;
@ -211,7 +211,7 @@ void Instance::refreshServerConfig() {
} }
void Instance::handleUpdate(const MTPDupdatePhoneCall& update) { void Instance::handleUpdate(const MTPDupdatePhoneCall& update) {
handleCallUpdate(update.vphone_call); handleCallUpdate(update.vphone_call());
} }
void Instance::showInfoPanel(not_null<Call*> call) { void Instance::showInfoPanel(not_null<Call*> call) {
@ -235,7 +235,7 @@ bool Instance::isQuitPrevent() {
void Instance::handleCallUpdate(const MTPPhoneCall &call) { void Instance::handleCallUpdate(const MTPPhoneCall &call) {
if (call.type() == mtpc_phoneCallRequested) { if (call.type() == mtpc_phoneCallRequested) {
auto &phoneCall = call.c_phoneCallRequested(); auto &phoneCall = call.c_phoneCallRequested();
auto user = Auth().data().userLoaded(phoneCall.vadmin_id.v); auto user = Auth().data().userLoaded(phoneCall.vadmin_id().v);
if (!user) { if (!user) {
LOG(("API Error: User not loaded for phoneCallRequested.")); LOG(("API Error: User not loaded for phoneCallRequested."));
} else if (user->isSelf()) { } else if (user->isSelf()) {
@ -244,12 +244,12 @@ void Instance::handleCallUpdate(const MTPPhoneCall &call) {
if (alreadyInCall() || !user || user->isSelf()) { if (alreadyInCall() || !user || user->isSelf()) {
request(MTPphone_DiscardCall( request(MTPphone_DiscardCall(
MTP_flags(0), MTP_flags(0),
MTP_inputPhoneCall(phoneCall.vid, phoneCall.vaccess_hash), MTP_inputPhoneCall(phoneCall.vid(), phoneCall.vaccess_hash()),
MTP_int(0), MTP_int(0),
MTP_phoneCallDiscardReasonBusy(), MTP_phoneCallDiscardReasonBusy(),
MTP_long(0) MTP_long(0)
)).send(); )).send();
} else if (phoneCall.vdate.v + (Global::CallRingTimeoutMs() / 1000) < unixtime()) { } else if (phoneCall.vdate().v + (Global::CallRingTimeoutMs() / 1000) < unixtime()) {
LOG(("Ignoring too old call.")); LOG(("Ignoring too old call."));
} else { } else {
createCall(user, Call::Type::Incoming); createCall(user, Call::Type::Incoming);

View file

@ -218,13 +218,13 @@ void ApplyDifference(
data.version = version; data.version = version;
for (const auto &keyword : keywords) { for (const auto &keyword : keywords) {
keyword.match([&](const MTPDemojiKeyword &keyword) { keyword.match([&](const MTPDemojiKeyword &keyword) {
const auto word = NormalizeKey(qs(keyword.vkeyword)); const auto word = NormalizeKey(qs(keyword.vkeyword()));
if (word.isEmpty()) { if (word.isEmpty()) {
return; return;
} }
auto &list = data.emoji[word]; auto &list = data.emoji[word];
auto &&emoji = ranges::view::all( auto &&emoji = ranges::view::all(
keyword.vemoticons.v keyword.vemoticons().v
) | ranges::view::transform([](const MTPstring &string) { ) | ranges::view::transform([](const MTPstring &string) {
const auto text = qs(string); const auto text = qs(string);
const auto emoji = MustAddPostfix(text) const auto emoji = MustAddPostfix(text)
@ -241,7 +241,7 @@ void ApplyDifference(
}); });
list.insert(end(list), emoji.begin(), emoji.end()); list.insert(end(list), emoji.begin(), emoji.end());
}, [&](const MTPDemojiKeywordDeleted &keyword) { }, [&](const MTPDemojiKeywordDeleted &keyword) {
const auto word = NormalizeKey(qs(keyword.vkeyword)); const auto word = NormalizeKey(qs(keyword.vkeyword()));
if (word.isEmpty()) { if (word.isEmpty()) {
return; return;
} }
@ -250,7 +250,7 @@ void ApplyDifference(
return; return;
} }
auto &list = i->second; auto &list = i->second;
for (const auto &emoji : keyword.vemoticons.v) { for (const auto &emoji : keyword.vemoticons().v) {
list.erase( list.erase(
ranges::remove(list, qs(emoji), &LangPackEmoji::text), ranges::remove(list, qs(emoji), &LangPackEmoji::text),
end(list)); end(list));
@ -388,9 +388,9 @@ void EmojiKeywords::LangPack::refresh() {
void EmojiKeywords::LangPack::applyDifference( void EmojiKeywords::LangPack::applyDifference(
const MTPEmojiKeywordsDifference &result) { const MTPEmojiKeywordsDifference &result) {
result.match([&](const MTPDemojiKeywordsDifference &data) { result.match([&](const MTPDemojiKeywordsDifference &data) {
const auto code = qs(data.vlang_code); const auto code = qs(data.vlang_code());
const auto version = data.vversion.v; const auto version = data.vversion().v;
const auto &keywords = data.vkeywords.v; const auto &keywords = data.vkeywords().v;
if (code != _id) { if (code != _id) {
LOG(("API Error: Bad lang_code for emoji keywords %1 -> %2" LOG(("API Error: Bad lang_code for emoji keywords %1 -> %2"
).arg(_id ).arg(_id
@ -634,7 +634,7 @@ void EmojiKeywords::refreshRemoteList() {
result.v result.v
) | ranges::view::transform([](const MTPEmojiLanguage &language) { ) | ranges::view::transform([](const MTPEmojiLanguage &language) {
return language.match([&](const MTPDemojiLanguage &language) { return language.match([&](const MTPDemojiLanguage &language) {
return qs(language.vlang_code); return qs(language.vlang_code());
}); });
}) | ranges::to_vector); }) | ranges::to_vector);
_langsRequestId = 0; _langsRequestId = 0;

View file

@ -228,16 +228,18 @@ void GifsListWidget::inlineResultsDone(const MTPmessages_BotResults &result) {
auto adding = (it != _inlineCache.cend()); auto adding = (it != _inlineCache.cend());
if (result.type() == mtpc_messages_botResults) { if (result.type() == mtpc_messages_botResults) {
auto &d = result.c_messages_botResults(); auto &d = result.c_messages_botResults();
Auth().data().processUsers(d.vusers); Auth().data().processUsers(d.vusers());
auto &v = d.vresults.v; auto &v = d.vresults().v;
auto queryId = d.vquery_id.v; auto queryId = d.vquery_id().v;
if (it == _inlineCache.cend()) { if (it == _inlineCache.cend()) {
it = _inlineCache.emplace(_inlineQuery, std::make_unique<InlineCacheEntry>()).first; it = _inlineCache.emplace(
_inlineQuery,
std::make_unique<InlineCacheEntry>()).first;
} }
auto entry = it->second.get(); auto entry = it->second.get();
entry->nextOffset = qs(d.vnext_offset); entry->nextOffset = qs(d.vnext_offset().value_or_empty());
if (auto count = v.size()) { if (auto count = v.size()) {
entry->results.reserve(entry->results.size() + count); entry->results.reserve(entry->results.size() + count);
} }
@ -853,9 +855,9 @@ void GifsListWidget::searchForGifs(const QString &query) {
Expects(result.type() == mtpc_contacts_resolvedPeer); Expects(result.type() == mtpc_contacts_resolvedPeer);
auto &data = result.c_contacts_resolvedPeer(); auto &data = result.c_contacts_resolvedPeer();
Auth().data().processUsers(data.vusers); Auth().data().processUsers(data.vusers());
Auth().data().processChats(data.vchats); Auth().data().processChats(data.vchats());
if (auto peer = Auth().data().peerLoaded(peerFromMTP(data.vpeer))) { if (auto peer = Auth().data().peerLoaded(peerFromMTP(data.vpeer()))) {
if (auto user = peer->asUser()) { if (auto user = peer->asUser()) {
_searchBot = user; _searchBot = user;
} }

View file

@ -31,7 +31,7 @@ constexpr auto kDontCacheLottieAfterArea = 512 * 512;
} // namespace } // namespace
void ApplyArchivedResult(const MTPDmessages_stickerSetInstallResultArchive &d) { void ApplyArchivedResult(const MTPDmessages_stickerSetInstallResultArchive &d) {
auto &v = d.vsets.v; auto &v = d.vsets().v;
auto &order = Auth().data().stickerSetsOrderRef(); auto &order = Auth().data().stickerSetsOrderRef();
Order archived; Order archived;
archived.reserve(v.size()); archived.reserve(v.size());
@ -41,14 +41,14 @@ void ApplyArchivedResult(const MTPDmessages_stickerSetInstallResultArchive &d) {
switch (stickerSet.type()) { switch (stickerSet.type()) {
case mtpc_stickerSetCovered: { case mtpc_stickerSetCovered: {
auto &d = stickerSet.c_stickerSetCovered(); auto &d = stickerSet.c_stickerSetCovered();
if (d.vset.type() == mtpc_stickerSet) { if (d.vset().type() == mtpc_stickerSet) {
setData = &d.vset.c_stickerSet(); setData = &d.vset().c_stickerSet();
} }
} break; } break;
case mtpc_stickerSetMultiCovered: { case mtpc_stickerSetMultiCovered: {
auto &d = stickerSet.c_stickerSetMultiCovered(); auto &d = stickerSet.c_stickerSetMultiCovered();
if (d.vset.type() == mtpc_stickerSet) { if (d.vset().type() == mtpc_stickerSet) {
setData = &d.vset.c_stickerSet(); setData = &d.vset().c_stickerSet();
} }
} break; } break;
} }
@ -97,7 +97,7 @@ bool ApplyArchivedResultFake() {
MTP_long(set.access), MTP_long(set.access),
MTP_string(set.title), MTP_string(set.title),
MTP_string(set.shortName), MTP_string(set.shortName),
MTP_photoSizeEmpty(MTP_string(QString())), MTP_photoSizeEmpty(MTP_string()),
MTP_int(0), MTP_int(0),
MTP_int(set.count), MTP_int(set.count),
MTP_int(set.hash)); MTP_int(set.hash));
@ -298,13 +298,13 @@ void RequestSetToPushFaved(not_null<DocumentData*> document) {
Expects(result.type() == mtpc_messages_stickerSet); Expects(result.type() == mtpc_messages_stickerSet);
auto list = std::vector<not_null<EmojiPtr>>(); auto list = std::vector<not_null<EmojiPtr>>();
auto &d = result.c_messages_stickerSet(); auto &d = result.c_messages_stickerSet();
list.reserve(d.vpacks.v.size()); list.reserve(d.vpacks().v.size());
for_const (auto &mtpPack, d.vpacks.v) { for_const (auto &mtpPack, d.vpacks().v) {
auto &pack = mtpPack.c_stickerPack(); auto &pack = mtpPack.c_stickerPack();
for_const (auto &documentId, pack.vdocuments.v) { for_const (auto &documentId, pack.vdocuments().v) {
if (documentId.v == document->id) { if (documentId.v == document->id) {
if (auto emoji = Ui::Emoji::Find(qs(mtpPack.c_stickerPack().vemoticon))) { if (const auto emoji = Ui::Emoji::Find(qs(mtpPack.c_stickerPack().vemoticon()))) {
list.push_back(emoji); list.emplace_back(emoji);
} }
break; break;
} }
@ -435,9 +435,9 @@ void SetPackAndEmoji(
for_const (auto &mtpPack, packs) { for_const (auto &mtpPack, packs) {
Assert(mtpPack.type() == mtpc_stickerPack); Assert(mtpPack.type() == mtpc_stickerPack);
auto &pack = mtpPack.c_stickerPack(); auto &pack = mtpPack.c_stickerPack();
if (auto emoji = Ui::Emoji::Find(qs(pack.vemoticon))) { if (auto emoji = Ui::Emoji::Find(qs(pack.vemoticon()))) {
emoji = emoji->original(); emoji = emoji->original();
auto &stickers = pack.vdocuments.v; auto &stickers = pack.vdocuments().v;
auto p = Pack(); auto p = Pack();
p.reserve(stickers.size()); p.reserve(stickers.size());
@ -584,49 +584,48 @@ void FeaturedSetsReceived(
switch (setData.type()) { switch (setData.type()) {
case mtpc_stickerSetCovered: { case mtpc_stickerSetCovered: {
auto &d = setData.c_stickerSetCovered(); auto &d = setData.c_stickerSetCovered();
if (d.vset.type() == mtpc_stickerSet) { if (d.vset().type() == mtpc_stickerSet) {
set = &d.vset.c_stickerSet(); set = &d.vset().c_stickerSet();
} }
} break; } break;
case mtpc_stickerSetMultiCovered: { case mtpc_stickerSetMultiCovered: {
auto &d = setData.c_stickerSetMultiCovered(); auto &d = setData.c_stickerSetMultiCovered();
if (d.vset.type() == mtpc_stickerSet) { if (d.vset().type() == mtpc_stickerSet) {
set = &d.vset.c_stickerSet(); set = &d.vset().c_stickerSet();
} }
} break; } break;
} }
if (set) { if (set) {
auto it = sets.find(set->vid.v); auto it = sets.find(set->vid().v);
const auto title = GetSetTitle(*set); const auto title = GetSetTitle(*set);
const auto installDate = set->has_installed_date() const auto installDate = set->vinstalled_date().value_or_empty();
? set->vinstalled_date.v const auto thumb = set->vthumb();
: TimeId(0); const auto thumbnail = thumb
const auto thumbnail = set->has_thumb() ? Images::Create(*set, *thumb)
? Images::Create(*set, set->vthumb)
: ImagePtr(); : ImagePtr();
if (it == sets.cend()) { if (it == sets.cend()) {
auto setClientFlags = MTPDstickerSet_ClientFlag::f_featured auto setClientFlags = MTPDstickerSet_ClientFlag::f_featured
| MTPDstickerSet_ClientFlag::f_not_loaded; | MTPDstickerSet_ClientFlag::f_not_loaded;
if (unreadMap.contains(set->vid.v)) { if (unreadMap.contains(set->vid().v)) {
setClientFlags |= MTPDstickerSet_ClientFlag::f_unread; setClientFlags |= MTPDstickerSet_ClientFlag::f_unread;
} }
it = sets.insert(set->vid.v, Set( it = sets.insert(set->vid().v, Set(
set->vid.v, set->vid().v,
set->vaccess_hash.v, set->vaccess_hash().v,
title, title,
qs(set->vshort_name), qs(set->vshort_name()),
set->vcount.v, set->vcount().v,
set->vhash.v, set->vhash().v,
set->vflags.v | setClientFlags, set->vflags().v | setClientFlags,
installDate, installDate,
thumbnail)); thumbnail));
} else { } else {
it->access = set->vaccess_hash.v; it->access = set->vaccess_hash().v;
it->title = title; it->title = title;
it->shortName = qs(set->vshort_name); it->shortName = qs(set->vshort_name());
auto clientFlags = it->flags & (MTPDstickerSet_ClientFlag::f_featured | MTPDstickerSet_ClientFlag::f_unread | MTPDstickerSet_ClientFlag::f_not_loaded | MTPDstickerSet_ClientFlag::f_special); auto clientFlags = it->flags & (MTPDstickerSet_ClientFlag::f_featured | MTPDstickerSet_ClientFlag::f_unread | MTPDstickerSet_ClientFlag::f_not_loaded | MTPDstickerSet_ClientFlag::f_special);
it->flags = set->vflags.v | clientFlags; it->flags = set->vflags().v | clientFlags;
it->flags |= MTPDstickerSet_ClientFlag::f_featured; it->flags |= MTPDstickerSet_ClientFlag::f_featured;
it->installDate = installDate; it->installDate = installDate;
it->thumbnail = thumbnail; it->thumbnail = thumbnail;
@ -635,15 +634,15 @@ void FeaturedSetsReceived(
} else { } else {
it->flags &= ~MTPDstickerSet_ClientFlag::f_unread; it->flags &= ~MTPDstickerSet_ClientFlag::f_unread;
} }
if (it->count != set->vcount.v || it->hash != set->vhash.v || it->emoji.isEmpty()) { if (it->count != set->vcount().v || it->hash != set->vhash().v || it->emoji.isEmpty()) {
it->count = set->vcount.v; it->count = set->vcount().v;
it->hash = set->vhash.v; it->hash = set->vhash().v;
it->flags |= MTPDstickerSet_ClientFlag::f_not_loaded; // need to request this set it->flags |= MTPDstickerSet_ClientFlag::f_not_loaded; // need to request this set
} }
} }
setsOrder.push_back(set->vid.v); setsOrder.push_back(set->vid().v);
if (it->stickers.isEmpty() || (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) { if (it->stickers.isEmpty() || (it->flags & MTPDstickerSet_ClientFlag::f_not_loaded)) {
setsToRequest.emplace(set->vid.v, set->vaccess_hash.v); setsToRequest.emplace(set->vid().v, set->vaccess_hash().v);
} }
} }
} }
@ -765,7 +764,7 @@ std::vector<not_null<DocumentData*>> GetListByEmoji(
const auto sticker = document->sticker(); const auto sticker = document->sticker();
if (sticker->set.type() == mtpc_inputStickerSetID) { if (sticker->set.type() == mtpc_inputStickerSetID) {
const auto setId = sticker->set.c_inputStickerSetID().vid.v; const auto setId = sticker->set.c_inputStickerSetID().vid().v;
const auto setIt = sets.find(setId); const auto setIt = sets.find(setId);
if (setIt != sets.end()) { if (setIt != sets.end()) {
return InstallDateAdjusted(setIt->installDate, document); return InstallDateAdjusted(setIt->installDate, document);
@ -874,7 +873,7 @@ std::optional<std::vector<not_null<EmojiPtr>>> GetEmojiListFromSet(
return std::nullopt; return std::nullopt;
} }
auto &sets = Auth().data().stickerSets(); auto &sets = Auth().data().stickerSets();
auto it = sets.constFind(inputSet.c_inputStickerSetID().vid.v); auto it = sets.constFind(inputSet.c_inputStickerSetID().vid().v);
if (it == sets.cend()) { if (it == sets.cend()) {
return std::nullopt; return std::nullopt;
} }
@ -894,43 +893,45 @@ std::optional<std::vector<not_null<EmojiPtr>>> GetEmojiListFromSet(
Set *FeedSet(const MTPDstickerSet &set) { Set *FeedSet(const MTPDstickerSet &set) {
auto &sets = Auth().data().stickerSetsRef(); auto &sets = Auth().data().stickerSetsRef();
auto it = sets.find(set.vid.v); auto it = sets.find(set.vid().v);
auto title = GetSetTitle(set); auto title = GetSetTitle(set);
auto flags = MTPDstickerSet::Flags(0); auto flags = MTPDstickerSet::Flags(0);
const auto thumb = set.vthumb();
const auto thumbnail = thumb ? Images::Create(set, *thumb) : ImagePtr();
if (it == sets.cend()) { if (it == sets.cend()) {
it = sets.insert(set.vid.v, Stickers::Set( it = sets.insert(set.vid().v, Stickers::Set(
set.vid.v, set.vid().v,
set.vaccess_hash.v, set.vaccess_hash().v,
title, title,
qs(set.vshort_name), qs(set.vshort_name()),
set.vcount.v, set.vcount().v,
set.vhash.v, set.vhash().v,
set.vflags.v | MTPDstickerSet_ClientFlag::f_not_loaded, set.vflags().v | MTPDstickerSet_ClientFlag::f_not_loaded,
set.has_installed_date() ? set.vinstalled_date.v : TimeId(0), set.vinstalled_date().value_or_empty(),
set.has_thumb() ? Images::Create(set, set.vthumb) : ImagePtr())); thumbnail));
} else { } else {
it->access = set.vaccess_hash.v; it->access = set.vaccess_hash().v;
it->title = title; it->title = title;
it->shortName = qs(set.vshort_name); it->shortName = qs(set.vshort_name());
flags = it->flags; flags = it->flags;
auto clientFlags = it->flags auto clientFlags = it->flags
& (MTPDstickerSet_ClientFlag::f_featured & (MTPDstickerSet_ClientFlag::f_featured
| MTPDstickerSet_ClientFlag::f_unread | MTPDstickerSet_ClientFlag::f_unread
| MTPDstickerSet_ClientFlag::f_not_loaded | MTPDstickerSet_ClientFlag::f_not_loaded
| MTPDstickerSet_ClientFlag::f_special); | MTPDstickerSet_ClientFlag::f_special);
it->flags = set.vflags.v | clientFlags; it->flags = set.vflags().v | clientFlags;
it->installDate = set.has_installed_date() const auto installDate = set.vinstalled_date();
? (set.vinstalled_date.v ? set.vinstalled_date.v : unixtime()) it->installDate = installDate
? (installDate->v ? installDate->v : unixtime())
: TimeId(0); : TimeId(0);
it->thumbnail = set.has_thumb() it->thumbnail = thumbnail;
? Images::Create(set, set.vthumb) if (it->count != set.vcount().v
: ImagePtr(); || it->hash != set.vhash().v
if (it->count != set.vcount.v
|| it->hash != set.vhash.v
|| it->emoji.isEmpty()) { || it->emoji.isEmpty()) {
it->count = set.vcount.v; // Need to request this set.
it->hash = set.vhash.v; it->count = set.vcount().v;
it->flags |= MTPDstickerSet_ClientFlag::f_not_loaded; // need to request this set it->hash = set.vhash().v;
it->flags |= MTPDstickerSet_ClientFlag::f_not_loaded;
} }
} }
auto changedFlags = (flags ^ it->flags); auto changedFlags = (flags ^ it->flags);
@ -949,20 +950,20 @@ Set *FeedSet(const MTPDstickerSet &set) {
Set *FeedSetFull(const MTPmessages_StickerSet &data) { Set *FeedSetFull(const MTPmessages_StickerSet &data) {
Expects(data.type() == mtpc_messages_stickerSet); Expects(data.type() == mtpc_messages_stickerSet);
Expects(data.c_messages_stickerSet().vset.type() == mtpc_stickerSet); Expects(data.c_messages_stickerSet().vset().type() == mtpc_stickerSet);
const auto &d = data.c_messages_stickerSet(); const auto &d = data.c_messages_stickerSet();
const auto &s = d.vset.c_stickerSet(); const auto &s = d.vset().c_stickerSet();
auto &sets = Auth().data().stickerSetsRef(); auto &sets = Auth().data().stickerSetsRef();
auto it = sets.find(s.vid.v); auto it = sets.find(s.vid().v);
const auto wasArchived = (it->flags & MTPDstickerSet::Flag::f_archived); const auto wasArchived = (it->flags & MTPDstickerSet::Flag::f_archived);
auto set = FeedSet(s); auto set = FeedSet(s);
set->flags &= ~MTPDstickerSet_ClientFlag::f_not_loaded; set->flags &= ~MTPDstickerSet_ClientFlag::f_not_loaded;
auto &d_docs = d.vdocuments.v; auto &d_docs = d.vdocuments().v;
auto custom = sets.find(Stickers::CustomSetId); auto custom = sets.find(Stickers::CustomSetId);
auto inputSet = MTP_inputStickerSetID( auto inputSet = MTP_inputStickerSetID(
MTP_long(set->id), MTP_long(set->id),
@ -1009,14 +1010,14 @@ Set *FeedSetFull(const MTPmessages_StickerSet &data) {
} else { } else {
set->stickers = pack; set->stickers = pack;
set->emoji.clear(); set->emoji.clear();
auto &v = d.vpacks.v; auto &v = d.vpacks().v;
for (auto i = 0, l = v.size(); i != l; ++i) { for (auto i = 0, l = v.size(); i != l; ++i) {
if (v[i].type() != mtpc_stickerPack) continue; if (v[i].type() != mtpc_stickerPack) continue;
auto &pack = v[i].c_stickerPack(); auto &pack = v[i].c_stickerPack();
if (auto emoji = Ui::Emoji::Find(qs(pack.vemoticon))) { if (auto emoji = Ui::Emoji::Find(qs(pack.vemoticon()))) {
emoji = emoji->original(); emoji = emoji->original();
auto &stickers = pack.vdocuments.v; auto &stickers = pack.vdocuments().v;
Pack p; Pack p;
p.reserve(stickers.size()); p.reserve(stickers.size());
@ -1058,8 +1059,8 @@ Set *FeedSetFull(const MTPmessages_StickerSet &data) {
void NewSetReceived(const MTPmessages_StickerSet &data) { void NewSetReceived(const MTPmessages_StickerSet &data) {
bool writeArchived = false; bool writeArchived = false;
const auto &set = data.c_messages_stickerSet(); const auto &set = data.c_messages_stickerSet();
const auto &s = set.vset.c_stickerSet(); const auto &s = set.vset().c_stickerSet();
if (!s.has_installed_date()) { if (!s.vinstalled_date()) {
LOG(("API Error: " LOG(("API Error: "
"updateNewStickerSet without install_date flag.")); "updateNewStickerSet without install_date flag."));
return; return;
@ -1071,20 +1072,20 @@ void NewSetReceived(const MTPmessages_StickerSet &data) {
return; return;
} }
auto &order = Auth().data().stickerSetsOrderRef(); auto &order = Auth().data().stickerSetsOrderRef();
int32 insertAtIndex = 0, currentIndex = order.indexOf(s.vid.v); int32 insertAtIndex = 0, currentIndex = order.indexOf(s.vid().v);
if (currentIndex != insertAtIndex) { if (currentIndex != insertAtIndex) {
if (currentIndex > 0) { if (currentIndex > 0) {
order.removeAt(currentIndex); order.removeAt(currentIndex);
} }
order.insert(insertAtIndex, s.vid.v); order.insert(insertAtIndex, s.vid().v);
} }
FeedSetFull(data); FeedSetFull(data);
} }
QString GetSetTitle(const MTPDstickerSet &s) { QString GetSetTitle(const MTPDstickerSet &s) {
auto title = qs(s.vtitle); auto title = qs(s.vtitle());
if ((s.vflags.v & MTPDstickerSet::Flag::f_official) && !title.compare(qstr("Great Minds"), Qt::CaseInsensitive)) { if ((s.vflags().v & MTPDstickerSet::Flag::f_official) && !title.compare(qstr("Great Minds"), Qt::CaseInsensitive)) {
return tr::lng_stickers_default_set(tr::now); return tr::lng_stickers_default_set(tr::now);
} }
return title; return title;

View file

@ -1250,22 +1250,22 @@ void StickersListWidget::searchResultsDone(
std::vector<uint64>()).first; std::vector<uint64>()).first;
} }
auto &d = result.c_messages_foundStickerSets(); auto &d = result.c_messages_foundStickerSets();
for (const auto &stickerSet : d.vsets.v) { for (const auto &stickerSet : d.vsets().v) {
const MTPDstickerSet *setData = nullptr; const MTPDstickerSet *setData = nullptr;
Stickers::Pack covers; Stickers::Pack covers;
switch (stickerSet.type()) { switch (stickerSet.type()) {
case mtpc_stickerSetCovered: { case mtpc_stickerSetCovered: {
auto &d = stickerSet.c_stickerSetCovered(); auto &d = stickerSet.c_stickerSetCovered();
if (d.vset.type() == mtpc_stickerSet) { if (d.vset().type() == mtpc_stickerSet) {
setData = &d.vset.c_stickerSet(); setData = &d.vset().c_stickerSet();
} }
} break; } break;
case mtpc_stickerSetMultiCovered: { case mtpc_stickerSetMultiCovered: {
auto &d = stickerSet.c_stickerSetMultiCovered(); auto &d = stickerSet.c_stickerSetMultiCovered();
if (d.vset.type() == mtpc_stickerSet) { if (d.vset().type() == mtpc_stickerSet) {
setData = &d.vset.c_stickerSet(); setData = &d.vset().c_stickerSet();
} }
for (const auto &cover : d.vcovers.v) { for (const auto &cover : d.vcovers().v) {
const auto document = Auth().data().processDocument(cover); const auto document = Auth().data().processDocument(cover);
if (document->sticker()) { if (document->sticker()) {
covers.push_back(document); covers.push_back(document);
@ -2408,7 +2408,7 @@ void StickersListWidget::refreshMegagroupStickers(GroupStickersPlace place) {
} }
auto &set = _megagroupSet->mgInfo->stickerSet.c_inputStickerSetID(); auto &set = _megagroupSet->mgInfo->stickerSet.c_inputStickerSetID();
auto &sets = Auth().data().stickerSets(); auto &sets = Auth().data().stickerSets();
auto it = sets.constFind(set.vid.v); auto it = sets.constFind(set.vid().v);
if (it != sets.cend()) { if (it != sets.cend()) {
auto isInstalled = (it->flags & MTPDstickerSet::Flag::f_installed_date) auto isInstalled = (it->flags & MTPDstickerSet::Flag::f_installed_date)
&& !(it->flags & MTPDstickerSet::Flag::f_archived); && !(it->flags & MTPDstickerSet::Flag::f_archived);
@ -2430,10 +2430,10 @@ void StickersListWidget::refreshMegagroupStickers(GroupStickersPlace place) {
} }
return; return;
} else if (!isShownHere(hidden) } else if (!isShownHere(hidden)
|| _megagroupSetIdRequested == set.vid.v) { || _megagroupSetIdRequested == set.vid().v) {
return; return;
} }
_megagroupSetIdRequested = set.vid.v; _megagroupSetIdRequested = set.vid().v;
request(MTPmessages_GetStickerSet( request(MTPmessages_GetStickerSet(
_megagroupSet->mgInfo->stickerSet _megagroupSet->mgInfo->stickerSet
)).done([=](const MTPmessages_StickerSet &result) { )).done([=](const MTPmessages_StickerSet &result) {
@ -2746,7 +2746,7 @@ void StickersListWidget::displaySet(uint64 setId) {
}); });
return; return;
} else if (_megagroupSet->mgInfo->stickerSet.type() == mtpc_inputStickerSetID) { } else if (_megagroupSet->mgInfo->stickerSet.type() == mtpc_inputStickerSetID) {
setId = _megagroupSet->mgInfo->stickerSet.c_inputStickerSetID().vid.v; setId = _megagroupSet->mgInfo->stickerSet.c_inputStickerSetID().vid().v;
} else { } else {
return; return;
} }

View file

@ -97,7 +97,7 @@ with open(input_file) as f:
layerline = re.match(r'// LAYER (\d+)', line) layerline = re.match(r'// LAYER (\d+)', line)
if (layerline): if (layerline):
layerIndex = int(layerline.group(1)); layerIndex = int(layerline.group(1));
layer = 'constexpr auto CurrentLayer = mtpPrime(' + str(layerIndex) + ');'; layer = 'inline constexpr mtpPrime CurrentLayer = mtpPrime(' + str(layerIndex) + ');';
else: else:
lines.append(line); lines.append(line);
@ -336,37 +336,38 @@ for line in lines:
funcsText += '\t\tMAX_FIELD = (1U << ' + str(maxbit) + '),\n'; funcsText += '\t\tMAX_FIELD = (1U << ' + str(maxbit) + '),\n';
funcsText += '\t};\n'; funcsText += '\t};\n';
funcsText += '\tusing Flags = base::flags<Flag>;\n'; funcsText += '\tusing Flags = base::flags<Flag>;\n';
funcsText += '\tfriend inline constexpr auto is_flag_type(Flag) { return true; };\n'; funcsText += '\tfriend inline constexpr bool is_flag_type(Flag) { return true; };\n';
funcsText += '\n'; funcsText += '\n';
if (len(conditions)):
for paramName in conditionsList:
if (paramName in trivialConditions):
funcsText += '\tbool is_' + paramName + '() const { return v' + hasFlags + '.v & Flag::f_' + paramName + '; }\n';
else:
funcsText += '\tbool has_' + paramName + '() const { return v' + hasFlags + '.v & Flag::f_' + paramName + '; }\n';
funcsText += '\n';
if (len(prms) > len(trivialConditions)): if (len(prms) > len(trivialConditions)):
for paramName in prmsList: for paramName in prmsList:
if (paramName in trivialConditions): if (paramName in trivialConditions):
continue; continue;
paramType = prms[paramName]; paramType = prms[paramName];
prmsInit.append('v' + paramName + '(_' + paramName + ')'); prmsInit.append('_' + paramName + '(' + paramName + '_)');
prmsNames.append('_' + paramName); prmsNames.append(paramName + '_');
if (paramName == isTemplate): if (paramName == isTemplate):
ptypeFull = paramType; ptypeFull = paramType;
else: else:
ptypeFull = 'MTP' + paramType; ptypeFull = 'MTP' + paramType;
funcsText += '\t' + ptypeFull + ' v' + paramName + ';\n';
if (paramType in ['int', 'Int', 'bool', 'Bool', 'flags<Flags>']): if (paramType in ['int', 'Int', 'bool', 'Bool', 'flags<Flags>']):
prmsStr.append(ptypeFull + ' _' + paramName); prmsStr.append(ptypeFull + ' ' + paramName + '_');
else: else:
prmsStr.append('const ' + ptypeFull + ' &_' + paramName); prmsStr.append('const ' + ptypeFull + ' &' + paramName + '_');
funcsText += '\n';
funcsText += '\tMTP' + name + '() = default;\n'; # constructor funcsText += '\tMTP' + name + '();\n';# = default; # constructor
if (isTemplate != ''):
methodBodies += 'template <typename TQueryType>\n'
methodBodies += 'MTP' + name + '<TQueryType>::MTP' + name + '() = default;\n';
else:
methodBodies += 'MTP' + name + '::MTP' + name + '() = default;\n';
if (len(prms) > len(trivialConditions)): if (len(prms) > len(trivialConditions)):
funcsText += '\tMTP' + name + '(' + ', '.join(prmsStr) + ') : ' + ', '.join(prmsInit) + ' {\n\t}\n'; funcsText += '\tMTP' + name + '(' + ', '.join(prmsStr) + ');\n';
if (isTemplate != ''):
methodBodies += 'template <typename TQueryType>\n'
methodBodies += 'MTP' + name + '<TQueryType>::MTP' + name + '(' + ', '.join(prmsStr) + ') : ' + ', '.join(prmsInit) + ' {\n}\n';
else:
methodBodies += 'MTP' + name + '::MTP' + name + '(' + ', '.join(prmsStr) + ') : ' + ', '.join(prmsInit) + ' {\n}\n';
funcsText += '\n'; funcsText += '\n';
funcsText += '\tuint32 innerLength() const;\n'; # count size funcsText += '\tuint32 innerLength() const;\n'; # count size
@ -380,9 +381,9 @@ for line in lines:
v = prms[k]; v = prms[k];
if (k in conditionsList): if (k in conditionsList):
if (not k in trivialConditions): if (not k in trivialConditions):
size.append('(has_' + k + '() ? v' + k + '.innerLength() : 0)'); size.append('((_' + hasFlags + '.v & Flag::f_' + k + ') ? _' + k + '.innerLength() : 0)');
else: else:
size.append('v' + k + '.innerLength()'); size.append('_' + k + '.innerLength()');
if (not len(size)): if (not len(size)):
size.append('0'); size.append('0');
methodBodies += '\treturn ' + ' + '.join(size) + ';\n'; methodBodies += '\treturn ' + ' + '.join(size) + ';\n';
@ -400,9 +401,9 @@ for line in lines:
v = prms[k]; v = prms[k];
if (k in conditionsList): if (k in conditionsList):
if (not k in trivialConditions): if (not k in trivialConditions):
methodBodies += '\tif (has_' + k + '()) { v' + k + '.read(from, end); } else { v' + k + ' = MTP' + v + '(); }\n'; methodBodies += '\tif (_' + hasFlags + '.v & Flag::f_' + k + ') { _' + k + '.read(from, end); } else { _' + k + ' = MTP' + v + '(); }\n';
else: else:
methodBodies += '\tv' + k + '.read(from, end);\n'; methodBodies += '\t_' + k + '.read(from, end);\n';
methodBodies += '}\n'; methodBodies += '}\n';
funcsText += '\tvoid write(mtpBuffer &to) const;\n'; # write method funcsText += '\tvoid write(mtpBuffer &to) const;\n'; # write method
@ -415,18 +416,31 @@ for line in lines:
v = prms[k]; v = prms[k];
if (k in conditionsList): if (k in conditionsList):
if (not k in trivialConditions): if (not k in trivialConditions):
methodBodies += '\tif (has_' + k + '()) v' + k + '.write(to);\n'; methodBodies += '\tif (_' + hasFlags + '.v & Flag::f_' + k + ') _' + k + '.write(to);\n';
else: else:
methodBodies += '\tv' + k + '.write(to);\n'; methodBodies += '\t_' + k + '.write(to);\n';
methodBodies += '}\n'; methodBodies += '}\n';
if (isTemplate != ''): if (isTemplate != ''):
funcsText += '\n\tusing ResponseType = typename TQueryType::ResponseType;\n'; funcsText += '\n\tusing ResponseType = typename TQueryType::ResponseType;\n\n';
inlineMethods += methodBodies; inlineMethods += methodBodies;
else: else:
funcsText += '\n\tusing ResponseType = MTP' + resType + ';\n'; # method return type funcsText += '\n\tusing ResponseType = MTP' + resType + ';\n\n'; # method return type
methods += methodBodies; methods += methodBodies;
if (len(prms) > len(trivialConditions)):
funcsText += 'private:\n';
for paramName in prmsList:
if (paramName in trivialConditions):
continue;
paramType = prms[paramName];
if (paramName == isTemplate):
ptypeFull = paramType;
else:
ptypeFull = 'MTP' + paramType;
funcsText += '\t' + ptypeFull + ' _' + paramName + ';\n';
funcsText += '\n';
funcsText += '};\n'; # class ending funcsText += '};\n'; # class ending
if (isTemplate != ''): if (isTemplate != ''):
funcsText += 'template <typename TQueryType>\n'; funcsText += 'template <typename TQueryType>\n';
@ -630,25 +644,27 @@ for restype in typesList:
dataText += '\t\tMAX_FIELD = (1U << ' + str(maxbit) + '),\n'; dataText += '\t\tMAX_FIELD = (1U << ' + str(maxbit) + '),\n';
dataText += '\t};\n'; dataText += '\t};\n';
dataText += '\tusing Flags = base::flags<Flag>;\n'; dataText += '\tusing Flags = base::flags<Flag>;\n';
dataText += '\tfriend inline constexpr auto is_flag_type(Flag) { return true; };\n'; dataText += '\tfriend inline constexpr bool is_flag_type(Flag) { return true; };\n';
dataText += '\n'; dataText += '\n';
if (len(conditions)): if (len(conditions)):
for paramName in conditionsList: for paramName in conditionsList:
if (paramName in trivialConditions): if (paramName in trivialConditions):
dataText += '\tbool is_' + paramName + '() const { return v' + hasFlags + '.v & Flag::f_' + paramName + '; }\n'; dataText += '\t[[nodiscard]] bool is_' + paramName + '() const;\n';
else: constructsBodies += 'bool MTPD' + name + '::is_' + paramName + '() const {\n';
dataText += '\tbool has_' + paramName + '() const { return v' + hasFlags + '.v & Flag::f_' + paramName + '; }\n'; constructsBodies += '\treturn _' + hasFlags + '.v & Flag::f_' + paramName + ';\n';
constructsBodies += '}\n';
dataText += '\n'; dataText += '\n';
switchLines += '\tcase mtpc_' + name + ': '; # for by-type-id type constructor switchLines += '\tcase mtpc_' + name + ': '; # for by-type-id type constructor
getters += '\tconst MTPD' + name + ' &c_' + name + '() const;\n'; # const getter getters += '\t[[nodiscard]] const MTPD' + name + ' &c_' + name + '() const;\n'; # const getter
visitor += '\tcase mtpc_' + name + ': return base::match_method(c_' + name + '(), std::forward<Method>(method), std::forward<Methods>(methods)...);\n'; visitor += '\tcase mtpc_' + name + ': return base::match_method(c_' + name + '(), std::forward<Method>(method), std::forward<Methods>(methods)...);\n';
forwards += 'class MTPD' + name + ';\n'; # data class forward declaration forwards += 'class MTPD' + name + ';\n'; # data class forward declaration
if (len(prms) > len(trivialConditions)): if (len(prms) > len(trivialConditions)):
dataText += '\tMTPD' + name + '() = default;\n'; # default constructor dataText += '\tMTPD' + name + '();\n'; # default constructor
switchLines += 'setData(new MTPD' + name + '()); '; switchLines += 'setData(new MTPD' + name + '()); ';
constructsBodies += 'MTPD' + name + '::MTPD' + name + '() = default;\n';
constructsBodies += 'const MTPD' + name + ' &MTP' + restype + '::c_' + name + '() const {\n'; constructsBodies += 'const MTPD' + name + ' &MTP' + restype + '::c_' + name + '() const {\n';
if (withType): if (withType):
constructsBodies += '\tExpects(_type == mtpc_' + name + ');\n\n'; constructsBodies += '\tExpects(_type == mtpc_' + name + ');\n\n';
@ -670,35 +686,59 @@ for restype in typesList:
paramType = prms[paramName]; paramType = prms[paramName];
if (paramType in ['int', 'Int', 'bool', 'Bool']): if (paramType in ['int', 'Int', 'bool', 'Bool']):
prmsStr.append('MTP' + paramType + ' _' + paramName); prmsStr.append('MTP' + paramType + ' ' + paramName + '_');
creatorParams.append('MTP' + paramType + ' _' + paramName); creatorParams.append('MTP' + paramType + ' ' + paramName + '_');
else: else:
prmsStr.append('const MTP' + paramType + ' &_' + paramName); prmsStr.append('const MTP' + paramType + ' &' + paramName + '_');
creatorParams.append('const MTP' + paramType + ' &_' + paramName); creatorParams.append('const MTP' + paramType + ' &' + paramName + '_');
creatorParamsList.append('_' + paramName); creatorParamsList.append(paramName + '_');
prmsInit.append('v' + paramName + '(_' + paramName + ')'); prmsInit.append('_' + paramName + '(' + paramName + '_)');
if (withType): if (withType):
readText += '\t'; readText += '\t';
writeText += '\t'; writeText += '\t';
if (paramName in conditions): if (paramName in conditions):
readText += '\tif (v->has_' + paramName + '()) { v->v' + paramName + '.read(from, end); } else { v->v' + paramName + ' = MTP' + paramType + '(); }\n'; readText += '\tif (v' + paramName + '()) { _' + paramName + '.read(from, end); } else { _' + paramName + ' = MTP' + paramType + '(); }\n';
writeText += '\tif (v.has_' + paramName + '()) v.v' + paramName + '.write(to);\n'; writeText += '\tif (const auto v' + paramName + ' = v.v' + paramName + '()) v' + paramName + '->write(to);\n';
sizeList.append('(v.has_' + paramName + '() ? v.v' + paramName + '.innerLength() : 0)'); sizeList.append('(v.v' + paramName + '() ? v.v' + paramName + '()->innerLength() : 0)');
else: else:
readText += '\tv->v' + paramName + '.read(from, end);\n'; readText += '\t_' + paramName + '.read(from, end);\n';
writeText += '\tv.v' + paramName + '.write(to);\n'; writeText += '\tv.v' + paramName + '().write(to);\n';
sizeList.append('v.v' + paramName + '.innerLength()'); sizeList.append('v.v' + paramName + '().innerLength()');
dataText += ', '.join(prmsStr) + ');\n'; dataText += ', '.join(prmsStr) + ');\n';
constructsBodies += 'MTPD' + name + '::MTPD' + name + '(' + ', '.join(prmsStr) + ') : ' + ', '.join(prmsInit) + ' {\n}\n'; constructsBodies += 'MTPD' + name + '::MTPD' + name + '(' + ', '.join(prmsStr) + ') : ' + ', '.join(prmsInit) + ' {\n}\n';
dataText += '\tMTPD' + name + '(const mtpPrime *&from, const mtpPrime *end);\n'; # reading constructor
constructsBodies += 'MTPD' + name + '::MTPD' + name + '(const mtpPrime *&from, const mtpPrime *end) {\n';
constructsBodies += readText;
constructsBodies += '}\n';
dataText += '\n'; dataText += '\n';
for paramName in prmsList: # fields declaration if len(prmsList) > 0:
if (paramName in trivialConditions): for paramName in prmsList: # getters
continue; if (paramName in trivialConditions):
paramType = prms[paramName]; continue;
dataText += '\tMTP' + paramType + ' v' + paramName + ';\n'; paramType = prms[paramName];
if (paramName in conditions):
dataText += '\t[[nodiscard]] MTP::conditional<MTP' + paramType + '> v' + paramName + '() const;\n';
constructsBodies += 'MTP::conditional<MTP' + paramType + '> MTPD' + name + '::v' + paramName + '() const {\n';
constructsBodies += '\treturn (_' + hasFlags + '.v & Flag::f_' + paramName + ') ? &_' + paramName + ' : nullptr;\n';
constructsBodies += '}\n';
else:
dataText += '\t[[nodiscard]] const MTP' + paramType + ' &v' + paramName + '() const;\n';
constructsBodies += 'const MTP' + paramType + ' &MTPD' + name + '::v' + paramName + '() const {\n';
constructsBodies += '\treturn _' + paramName + ';\n';
constructsBodies += '}\n';
dataText += '\n';
dataText += 'private:\n';
for paramName in prmsList: # fields declaration
if (paramName in trivialConditions):
continue;
paramType = prms[paramName];
dataText += '\tMTP' + paramType + ' _' + paramName + ';\n';
dataText += '\n';
sizeCases += '\tcase mtpc_' + name + ': {\n'; sizeCases += '\tcase mtpc_' + name + ': {\n';
sizeCases += '\t\tconst MTPD' + name + ' &v(c_' + name + '());\n'; sizeCases += '\t\tconst MTPD' + name + ' &v(c_' + name + '());\n';
sizeCases += '\t\treturn ' + ' + '.join(sizeList) + ';\n'; sizeCases += '\t\treturn ' + ' + '.join(sizeList) + ';\n';
@ -740,24 +780,20 @@ for restype in typesList:
reader += '\tcase mtpc_' + name + ': _type = cons; '; # read switch line reader += '\tcase mtpc_' + name + ': _type = cons; '; # read switch line
if (len(prms) > len(trivialConditions)): if (len(prms) > len(trivialConditions)):
reader += '{\n'; reader += '{\n';
reader += '\t\tauto v = new MTPD' + name + '();\n'; reader += '\t\tsetData(new MTPD' + name + '(from, end));\n';
reader += '\t\tsetData(v);\n';
reader += readText;
reader += '\t} break;\n'; reader += '\t} break;\n';
writer += '\tcase mtpc_' + name + ': {\n'; # write switch line writer += '\tcase mtpc_' + name + ': {\n'; # write switch line
writer += '\t\tauto &v = c_' + name + '();\n'; writer += '\t\tconst MTPD' + name + ' &v = c_' + name + '();\n';
writer += writeText; writer += writeText;
writer += '\t} break;\n'; writer += '\t} break;\n';
else: else:
reader += 'break;\n'; reader += 'break;\n';
else: else:
if (len(prms) > len(trivialConditions)): if (len(prms) > len(trivialConditions)):
reader += '\n\tauto v = new MTPD' + name + '();\n'; reader += '\tsetData(new MTPD' + name + '(from, end));\n';
reader += '\tsetData(v);\n';
reader += readText;
writer += '\tconst auto &v = c_' + name + '();\n'; writer += '\tconst MTPD' + name + ' &v = c_' + name + '();\n';
writer += writeText; writer += writeText;
forwards += '\n'; forwards += '\n';
@ -767,12 +803,11 @@ for restype in typesList:
typesText += ' : private MTP::internal::TypeDataOwner'; # if has data fields typesText += ' : private MTP::internal::TypeDataOwner'; # if has data fields
typesText += ' {\n'; typesText += ' {\n';
typesText += 'public:\n'; typesText += 'public:\n';
typesText += '\tMTP' + restype + '()'; # default constructor typesText += '\tMTP' + restype + '();\n'; # default constructor
if (withData and not withType): if (withData and not withType):
typesText += ';\n';
methods += '\nMTP' + restype + '::MTP' + restype + '() : TypeDataOwner(' + newFast + ') {\n}\n'; methods += '\nMTP' + restype + '::MTP' + restype + '() : TypeDataOwner(' + newFast + ') {\n}\n';
else: else:
typesText += ' = default;\n'; methods += '\nMTP' + restype + '::MTP' + restype + '() = default;\n';
typesText += getters; typesText += getters;
typesText += '\n'; typesText += '\n';

View file

@ -104,10 +104,10 @@ void Changelogs::requestCloudLogs() {
resultEmpty = false; resultEmpty = false;
break; break;
case mtpc_updatesCombined: case mtpc_updatesCombined:
resultEmpty = result.c_updatesCombined().vupdates.v.isEmpty(); resultEmpty = result.c_updatesCombined().vupdates().v.isEmpty();
break; break;
case mtpc_updates: case mtpc_updates:
resultEmpty = result.c_updates().vupdates.v.isEmpty(); resultEmpty = result.c_updates().vupdates().v.isEmpty();
break; break;
case mtpc_updatesTooLong: case mtpc_updatesTooLong:
case mtpc_updateShortSentMessage: case mtpc_updateShortSentMessage:

View file

@ -179,10 +179,10 @@ bytes::vector ComputeHash(
CloudPasswordAlgo ParseCloudPasswordAlgo(const MTPPasswordKdfAlgo &data) { CloudPasswordAlgo ParseCloudPasswordAlgo(const MTPPasswordKdfAlgo &data) {
return data.match([](const MTPDpasswordKdfAlgoModPow &data) { return data.match([](const MTPDpasswordKdfAlgoModPow &data) {
return CloudPasswordAlgo(CloudPasswordAlgoModPow{ return CloudPasswordAlgo(CloudPasswordAlgoModPow{
bytes::make_vector(data.vsalt1.v), bytes::make_vector(data.vsalt1().v),
bytes::make_vector(data.vsalt2.v), bytes::make_vector(data.vsalt2().v),
data.vg.v, data.vg().v,
bytes::make_vector(data.vp.v) }); bytes::make_vector(data.vp().v) });
}, [](const MTPDpasswordKdfAlgoUnknown &data) { }, [](const MTPDpasswordKdfAlgoUnknown &data) {
return CloudPasswordAlgo(); return CloudPasswordAlgo();
}); });
@ -190,14 +190,11 @@ CloudPasswordAlgo ParseCloudPasswordAlgo(const MTPPasswordKdfAlgo &data) {
CloudPasswordCheckRequest ParseCloudPasswordCheckRequest( CloudPasswordCheckRequest ParseCloudPasswordCheckRequest(
const MTPDaccount_password &data) { const MTPDaccount_password &data) {
const auto algo = data.vcurrent_algo();
return CloudPasswordCheckRequest{ return CloudPasswordCheckRequest{
(data.has_srp_id() ? data.vsrp_id.v : uint64()), data.vsrp_id().value_or_empty(),
(data.has_srp_B() bytes::make_vector(data.vsrp_B().value_or_empty()),
? bytes::make_vector(data.vsrp_B.v) (algo ? ParseCloudPasswordAlgo(*algo) : CloudPasswordAlgo())
: bytes::vector()),
(data.has_current_algo()
? ParseCloudPasswordAlgo(data.vcurrent_algo)
: CloudPasswordAlgo())
}; };
} }
@ -263,10 +260,10 @@ SecureSecretAlgo ParseSecureSecretAlgo(
return data.match([]( return data.match([](
const MTPDsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000 &data) { const MTPDsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000 &data) {
return SecureSecretAlgo(SecureSecretAlgoPBKDF2{ return SecureSecretAlgo(SecureSecretAlgoPBKDF2{
bytes::make_vector(data.vsalt.v) }); bytes::make_vector(data.vsalt().v) });
}, [](const MTPDsecurePasswordKdfAlgoSHA512 &data) { }, [](const MTPDsecurePasswordKdfAlgoSHA512 &data) {
return SecureSecretAlgo(SecureSecretAlgoSHA512{ return SecureSecretAlgo(SecureSecretAlgoSHA512{
bytes::make_vector(data.vsalt.v) }); bytes::make_vector(data.vsalt().v) });
}, [](const MTPDsecurePasswordKdfAlgoUnknown &data) { }, [](const MTPDsecurePasswordKdfAlgoUnknown &data) {
return SecureSecretAlgo(); return SecureSecretAlgo();
}); });
@ -307,17 +304,16 @@ CloudPasswordState ParseCloudPasswordState(
const MTPDaccount_password &data) { const MTPDaccount_password &data) {
auto result = CloudPasswordState(); auto result = CloudPasswordState();
result.request = ParseCloudPasswordCheckRequest(data); result.request = ParseCloudPasswordCheckRequest(data);
result.unknownAlgorithm = data.has_current_algo() && !result.request; result.unknownAlgorithm = data.vcurrent_algo() && !result.request;
result.hasRecovery = data.is_has_recovery(); result.hasRecovery = data.is_has_recovery();
result.notEmptyPassport = data.is_has_secure_values(); result.notEmptyPassport = data.is_has_secure_values();
result.hint = data.has_hint() ? qs(data.vhint) : QString(); result.hint = qs(data.vhint().value_or_empty());
result.newPassword = ValidateNewCloudPasswordAlgo( result.newPassword = ValidateNewCloudPasswordAlgo(
ParseCloudPasswordAlgo(data.vnew_algo)); ParseCloudPasswordAlgo(data.vnew_algo()));
result.newSecureSecret = ValidateNewSecureSecretAlgo( result.newSecureSecret = ValidateNewSecureSecretAlgo(
ParseSecureSecretAlgo(data.vnew_secure_algo)); ParseSecureSecretAlgo(data.vnew_secure_algo()));
result.unconfirmedPattern = data.has_email_unconfirmed_pattern() result.unconfirmedPattern =
? qs(data.vemail_unconfirmed_pattern) qs(data.vemail_unconfirmed_pattern().value_or_empty());
: QString();
return result; return result;
} }

View file

@ -45,7 +45,7 @@ bool JoinGroupByHash(const Match &match, const QVariant &context) {
Auth().api().importChatInvite(hash); Auth().api().importChatInvite(hash);
})); }));
}, [=](const MTPDchatInviteAlready &data) { }, [=](const MTPDchatInviteAlready &data) {
if (const auto chat = Auth().data().processChat(data.vchat)) { if (const auto chat = Auth().data().processChat(data.vchat())) {
App::wnd()->sessionController()->showPeerHistory( App::wnd()->sessionController()->showPeerHistory(
chat, chat,
Window::SectionShow::Way::Forward); Window::SectionShow::Way::Forward);
@ -260,7 +260,7 @@ bool ResolvePrivatePost(const Match &match, const QVariant &context) {
MTP_inputChannel(MTP_int(channelId), MTP_long(0))) MTP_inputChannel(MTP_int(channelId), MTP_long(0)))
)).done([=](const MTPmessages_Chats &result) { )).done([=](const MTPmessages_Chats &result) {
result.match([&](const auto &data) { result.match([&](const auto &data) {
const auto peer = auth->data().processChats(data.vchats); const auto peer = auth->data().processChats(data.vchats());
if (peer && peer->id == peerFromChannel(channelId)) { if (peer && peer->id == peerFromChannel(channelId)) {
done(peer); done(peer);
} else { } else {
@ -280,10 +280,9 @@ bool HandleUnknown(const Match &match, const QVariant &context) {
const auto request = match->captured(1); const auto request = match->captured(1);
const auto callback = [=](const MTPDhelp_deepLinkInfo &result) { const auto callback = [=](const MTPDhelp_deepLinkInfo &result) {
const auto text = TextWithEntities{ const auto text = TextWithEntities{
qs(result.vmessage), qs(result.vmessage()),
(result.has_entities() TextUtilities::EntitiesFromMTP(
? TextUtilities::EntitiesFromMTP(result.ventities.v) result.ventities().value_or_empty())
: EntitiesInText())
}; };
if (result.is_update_app()) { if (result.is_update_app()) {
const auto box = std::make_shared<QPointer<BoxContent>>(); const auto box = std::make_shared<QPointer<BoxContent>>();

View file

@ -896,8 +896,8 @@ void MtpChecker::start() {
_mtp.send( _mtp.send(
MTPmessages_GetHistory( MTPmessages_GetHistory(
MTP_inputPeerChannel( MTP_inputPeerChannel(
channel.c_inputChannel().vchannel_id, channel.c_inputChannel().vchannel_id(),
channel.c_inputChannel().vaccess_hash), channel.c_inputChannel().vaccess_hash()),
MTP_int(0), // offset_id MTP_int(0), // offset_id
MTP_int(0), // offset_date MTP_int(0), // offset_date
MTP_int(0), // add_offset MTP_int(0), // add_offset
@ -936,7 +936,7 @@ auto MtpChecker::parseMessage(const MTPmessages_Messages &result) const
LOG(("Update Error: MTP feed message not found.")); LOG(("Update Error: MTP feed message not found."));
return std::nullopt; return std::nullopt;
} }
return parseText(message->c_message().vmessage.v); return parseText(message->c_message().vmessage().v);
} }
auto MtpChecker::parseText(const QByteArray &text) const auto MtpChecker::parseText(const QByteArray &text) const

View file

@ -75,7 +75,7 @@ void ChannelData::setPhoto(const MTPChatPhoto &photo) {
void ChannelData::setPhoto(PhotoId photoId, const MTPChatPhoto &photo) { void ChannelData::setPhoto(PhotoId photoId, const MTPChatPhoto &photo) {
photo.match([&](const MTPDchatPhoto & data) { photo.match([&](const MTPDchatPhoto & data) {
updateUserpic(photoId, data.vdc_id.v, data.vphoto_small); updateUserpic(photoId, data.vdc_id().v, data.vphoto_small());
}, [&](const MTPDchatPhotoEmpty &) { }, [&](const MTPDchatPhotoEmpty &) {
clearUserpic(); clearUserpic();
}); });
@ -108,9 +108,9 @@ void ChannelData::setLocation(const MTPChannelLocation &data) {
const auto was = mgInfo->getLocation(); const auto was = mgInfo->getLocation();
const auto wasValue = was ? *was : ChannelLocation(); const auto wasValue = was ? *was : ChannelLocation();
data.match([&](const MTPDchannelLocation &data) { data.match([&](const MTPDchannelLocation &data) {
data.vgeo_point.match([&](const MTPDgeoPoint &point) { data.vgeo_point().match([&](const MTPDgeoPoint &point) {
mgInfo->setLocation({ mgInfo->setLocation({
qs(data.vaddress), qs(data.vaddress()),
Data::LocationPoint(point) Data::LocationPoint(point)
}); });
}, [&](const MTPDgeoPointEmpty &) { }, [&](const MTPDgeoPointEmpty &) {
@ -216,7 +216,7 @@ void ChannelData::applyEditAdmin(
auto userId = peerToUser(user->id); auto userId = peerToUser(user->id);
auto it = mgInfo->lastAdmins.find(user); auto it = mgInfo->lastAdmins.find(user);
if (newRights.c_chatAdminRights().vflags.v != 0) { if (newRights.c_chatAdminRights().vflags().v != 0) {
auto lastAdmin = MegagroupInfo::Admin { newRights }; auto lastAdmin = MegagroupInfo::Admin { newRights };
lastAdmin.canEdit = true; lastAdmin.canEdit = true;
if (it == mgInfo->lastAdmins.cend()) { if (it == mgInfo->lastAdmins.cend()) {
@ -236,7 +236,7 @@ void ChannelData::applyEditAdmin(
Data::ChannelAdminChanges(this).feed(userId, false); Data::ChannelAdminChanges(this).feed(userId, false);
} }
} }
if (oldRights.c_chatAdminRights().vflags.v && !newRights.c_chatAdminRights().vflags.v) { if (oldRights.c_chatAdminRights().vflags().v && !newRights.c_chatAdminRights().vflags().v) {
// We removed an admin. // We removed an admin.
if (adminsCount() > 1) { if (adminsCount() > 1) {
setAdminsCount(adminsCount() - 1); setAdminsCount(adminsCount() - 1);
@ -245,7 +245,7 @@ void ChannelData::applyEditAdmin(
// Removing bot admin removes it from channel. // Removing bot admin removes it from channel.
setMembersCount(membersCount() - 1); setMembersCount(membersCount() - 1);
} }
} else if (!oldRights.c_chatAdminRights().vflags.v && newRights.c_chatAdminRights().vflags.v) { } else if (!oldRights.c_chatAdminRights().vflags().v && newRights.c_chatAdminRights().vflags().v) {
// We added an admin. // We added an admin.
setAdminsCount(adminsCount() + 1); setAdminsCount(adminsCount() + 1);
updateFullForced(); updateFullForced();
@ -257,8 +257,8 @@ void ChannelData::applyEditAdmin(
void ChannelData::applyEditBanned(not_null<UserData*> user, const MTPChatBannedRights &oldRights, const MTPChatBannedRights &newRights) { void ChannelData::applyEditBanned(not_null<UserData*> user, const MTPChatBannedRights &oldRights, const MTPChatBannedRights &newRights) {
auto flags = Notify::PeerUpdate::Flag::BannedUsersChanged | Notify::PeerUpdate::Flag::None; auto flags = Notify::PeerUpdate::Flag::BannedUsersChanged | Notify::PeerUpdate::Flag::None;
auto isKicked = (newRights.c_chatBannedRights().vflags.v & MTPDchatBannedRights::Flag::f_view_messages); auto isKicked = (newRights.c_chatBannedRights().vflags().v & MTPDchatBannedRights::Flag::f_view_messages);
auto isRestricted = !isKicked && (newRights.c_chatBannedRights().vflags.v != 0); auto isRestricted = !isKicked && (newRights.c_chatBannedRights().vflags().v != 0);
if (mgInfo) { if (mgInfo) {
// If rights are empty - still remove admin? TODO check // If rights are empty - still remove admin? TODO check
if (mgInfo->lastAdmins.contains(user)) { if (mgInfo->lastAdmins.contains(user)) {
@ -496,10 +496,10 @@ bool ChannelData::canRestrictUser(not_null<UserData*> user) const {
} }
void ChannelData::setAdminRights(const MTPChatAdminRights &rights) { void ChannelData::setAdminRights(const MTPChatAdminRights &rights) {
if (rights.c_chatAdminRights().vflags.v == adminRights()) { if (rights.c_chatAdminRights().vflags().v == adminRights()) {
return; return;
} }
_adminRights.set(rights.c_chatAdminRights().vflags.v); _adminRights.set(rights.c_chatAdminRights().vflags().v);
if (isMegagroup()) { if (isMegagroup()) {
const auto self = session().user(); const auto self = session().user();
if (hasAdminRights()) { if (hasAdminRights()) {
@ -520,12 +520,12 @@ void ChannelData::setAdminRights(const MTPChatAdminRights &rights) {
} }
void ChannelData::setRestrictions(const MTPChatBannedRights &rights) { void ChannelData::setRestrictions(const MTPChatBannedRights &rights) {
if (rights.c_chatBannedRights().vflags.v == restrictions() if (rights.c_chatBannedRights().vflags().v == restrictions()
&& rights.c_chatBannedRights().vuntil_date.v == _restrictedUntil) { && rights.c_chatBannedRights().vuntil_date().v == _restrictedUntil) {
return; return;
} }
_restrictedUntil = rights.c_chatBannedRights().vuntil_date.v; _restrictedUntil = rights.c_chatBannedRights().vuntil_date().v;
_restrictions.set(rights.c_chatBannedRights().vflags.v); _restrictions.set(rights.c_chatBannedRights().vflags().v);
if (isMegagroup()) { if (isMegagroup()) {
const auto self = session().user(); const auto self = session().user();
if (hasRestrictions()) { if (hasRestrictions()) {
@ -543,10 +543,10 @@ void ChannelData::setRestrictions(const MTPChatBannedRights &rights) {
} }
void ChannelData::setDefaultRestrictions(const MTPChatBannedRights &rights) { void ChannelData::setDefaultRestrictions(const MTPChatBannedRights &rights) {
if (rights.c_chatBannedRights().vflags.v == defaultRestrictions()) { if (rights.c_chatBannedRights().vflags().v == defaultRestrictions()) {
return; return;
} }
_defaultRestrictions.set(rights.c_chatBannedRights().vflags.v); _defaultRestrictions.set(rights.c_chatBannedRights().vflags().v);
Notify::peerUpdatedDelayed(this, UpdateFlag::RightsChanged); Notify::peerUpdatedDelayed(this, UpdateFlag::RightsChanged);
} }
@ -594,69 +594,63 @@ void ApplyMigration(
void ApplyChannelUpdate( void ApplyChannelUpdate(
not_null<ChannelData*> channel, not_null<ChannelData*> channel,
const MTPDupdateChatDefaultBannedRights &update) { const MTPDupdateChatDefaultBannedRights &update) {
if (channel->applyUpdateVersion(update.vversion.v) if (channel->applyUpdateVersion(update.vversion().v)
!= ChannelData::UpdateStatus::Good) { != ChannelData::UpdateStatus::Good) {
return; return;
} }
channel->setDefaultRestrictions(update.vdefault_banned_rights); channel->setDefaultRestrictions(update.vdefault_banned_rights());
} }
void ApplyChannelUpdate( void ApplyChannelUpdate(
not_null<ChannelData*> channel, not_null<ChannelData*> channel,
const MTPDchannelFull &update) { const MTPDchannelFull &update) {
channel->setAvailableMinId(update.vavailable_min_id.v); channel->setAvailableMinId(update.vavailable_min_id().value_or_empty());
auto canViewAdmins = channel->canViewAdmins(); auto canViewAdmins = channel->canViewAdmins();
auto canViewMembers = channel->canViewMembers(); auto canViewMembers = channel->canViewMembers();
auto canEditStickers = channel->canEditStickers(); auto canEditStickers = channel->canEditStickers();
channel->setFullFlags(update.vflags.v); channel->setFullFlags(update.vflags().v);
channel->setUserpicPhoto(update.vchat_photo); channel->setUserpicPhoto(update.vchat_photo());
if (update.has_migrated_from_chat_id()) { if (const auto migratedFrom = update.vmigrated_from_chat_id()) {
channel->addFlags(MTPDchannel::Flag::f_megagroup); channel->addFlags(MTPDchannel::Flag::f_megagroup);
const auto chat = channel->owner().chat( const auto chat = channel->owner().chat(migratedFrom->v);
update.vmigrated_from_chat_id.v);
Data::ApplyMigration(chat, channel); Data::ApplyMigration(chat, channel);
} }
for (const auto &item : update.vbot_info.v) { for (const auto &item : update.vbot_info().v) {
auto &owner = channel->owner(); auto &owner = channel->owner();
item.match([&](const MTPDbotInfo &info) { item.match([&](const MTPDbotInfo &info) {
if (const auto user = owner.userLoaded(info.vuser_id.v)) { if (const auto user = owner.userLoaded(info.vuser_id().v)) {
user->setBotInfo(item); user->setBotInfo(item);
channel->session().api().fullPeerUpdated().notify(user); channel->session().api().fullPeerUpdated().notify(user);
} }
}); });
} }
channel->setAbout(qs(update.vabout)); channel->setAbout(qs(update.vabout()));
channel->setMembersCount(update.has_participants_count() channel->setMembersCount(update.vparticipants_count().value_or_empty());
? update.vparticipants_count.v channel->setAdminsCount(update.vadmins_count().value_or_empty());
: 0); channel->setRestrictedCount(update.vbanned_count().value_or_empty());
channel->setAdminsCount(update.has_admins_count() channel->setKickedCount(update.vkicked_count().value_or_empty());
? update.vadmins_count.v channel->setInviteLink(update.vexported_invite().match([&](
: 0);
channel->setRestrictedCount(update.has_banned_count()
? update.vbanned_count.v
: 0);
channel->setKickedCount(update.has_kicked_count()
? update.vkicked_count.v
: 0);
channel->setInviteLink(update.vexported_invite.match([&](
const MTPDchatInviteExported &data) { const MTPDchatInviteExported &data) {
return qs(data.vlink); return qs(data.vlink());
}, [&](const MTPDchatInviteEmpty &) { }, [&](const MTPDchatInviteEmpty &) {
return QString(); return QString();
})); }));
channel->setLocation(update.has_location() if (const auto location = update.vlocation()) {
? update.vlocation channel->setLocation(*location);
: MTPChannelLocation(MTP_channelLocationEmpty())); } else {
channel->setLinkedChat(update.has_linked_chat_id() channel->setLocation(MTP_channelLocationEmpty());
? channel->owner().channelLoaded(update.vlinked_chat_id.v) }
: nullptr); if (const auto chat = update.vlinked_chat_id()) {
channel->setLinkedChat(channel->owner().channelLoaded(chat->v));
} else {
channel->setLinkedChat(nullptr);
}
if (const auto history = channel->owner().historyLoaded(channel)) { if (const auto history = channel->owner().historyLoaded(channel)) {
history->clearUpTill(update.vavailable_min_id.v); if (const auto available = update.vavailable_min_id()) {
history->clearUpTill(available->v);
const auto folderId = update.has_folder_id() }
? update.vfolder_id.v const auto folderId = update.vfolder_id().value_or_empty();
: 0;
const auto folder = folderId const auto folder = folderId
? channel->owner().folderLoaded(folderId) ? channel->owner().folderLoaded(folderId)
: nullptr; : nullptr;
@ -665,34 +659,33 @@ void ApplyChannelUpdate(
channel->session().api().requestDialogEntry(history); channel->session().api().requestDialogEntry(history);
channel->session().api().requestDialogEntry(folder); channel->session().api().requestDialogEntry(folder);
} else if (!history->folderKnown() } else if (!history->folderKnown()
|| channel->pts() != update.vpts.v) { || channel->pts() != update.vpts().v) {
channel->session().api().requestDialogEntry(history); channel->session().api().requestDialogEntry(history);
} else { } else {
history->applyDialogFields( history->applyDialogFields(
history->folder(), history->folder(),
update.vunread_count.v, update.vunread_count().v,
update.vread_inbox_max_id.v, update.vread_inbox_max_id().v,
update.vread_outbox_max_id.v); update.vread_outbox_max_id().v);
} }
} }
if (update.has_pinned_msg_id()) { if (const auto pinned = update.vpinned_msg_id()) {
channel->setPinnedMessageId(update.vpinned_msg_id.v); channel->setPinnedMessageId(pinned->v);
} else { } else {
channel->clearPinnedMessage(); channel->clearPinnedMessage();
} }
if (channel->isMegagroup()) { if (channel->isMegagroup()) {
const auto stickerSet = update.has_stickerset() const auto stickerSet = update.vstickerset();
? &update.vstickerset.c_stickerSet() const auto set = stickerSet ? &stickerSet->c_stickerSet() : nullptr;
: nullptr; const auto newSetId = (set ? set->vid().v : 0);
const auto newSetId = (stickerSet ? stickerSet->vid.v : 0);
const auto oldSetId = (channel->mgInfo->stickerSet.type() == mtpc_inputStickerSetID) const auto oldSetId = (channel->mgInfo->stickerSet.type() == mtpc_inputStickerSetID)
? channel->mgInfo->stickerSet.c_inputStickerSetID().vid.v ? channel->mgInfo->stickerSet.c_inputStickerSetID().vid().v
: 0; : 0;
const auto stickersChanged = (canEditStickers != channel->canEditStickers()) const auto stickersChanged = (canEditStickers != channel->canEditStickers())
|| (oldSetId != newSetId); || (oldSetId != newSetId);
if (oldSetId != newSetId) { if (oldSetId != newSetId) {
channel->mgInfo->stickerSet = stickerSet channel->mgInfo->stickerSet = set
? MTP_inputStickerSetID(stickerSet->vid, stickerSet->vaccess_hash) ? MTP_inputStickerSetID(set->vid(), set->vaccess_hash())
: MTP_inputStickerSetEmpty(); : MTP_inputStickerSetEmpty();
} }
if (stickersChanged) { if (stickersChanged) {
@ -712,7 +705,7 @@ void ApplyChannelUpdate(
channel->session().api().applyNotifySettings( channel->session().api().applyNotifySettings(
MTP_inputNotifyPeer(channel->input), MTP_inputNotifyPeer(channel->input),
update.vnotify_settings); update.vnotify_settings());
} }
} // namespace Data } // namespace Data

View file

@ -32,7 +32,7 @@ void ChatData::setPhoto(const MTPChatPhoto &photo) {
void ChatData::setPhoto(PhotoId photoId, const MTPChatPhoto &photo) { void ChatData::setPhoto(PhotoId photoId, const MTPChatPhoto &photo) {
photo.match([&](const MTPDchatPhoto &data) { photo.match([&](const MTPDchatPhoto &data) {
updateUserpic(photoId, data.vdc_id.v, data.vphoto_small); updateUserpic(photoId, data.vdc_id().v, data.vphoto_small());
}, [&](const MTPDchatPhotoEmpty &) { }, [&](const MTPDchatPhotoEmpty &) {
clearUserpic(); clearUserpic();
}); });
@ -128,10 +128,10 @@ void ChatData::setInviteLink(const QString &newInviteLink) {
} }
void ChatData::setAdminRights(const MTPChatAdminRights &rights) { void ChatData::setAdminRights(const MTPChatAdminRights &rights) {
if (rights.c_chatAdminRights().vflags.v == adminRights()) { if (rights.c_chatAdminRights().vflags().v == adminRights()) {
return; return;
} }
_adminRights.set(rights.c_chatAdminRights().vflags.v); _adminRights.set(rights.c_chatAdminRights().vflags().v);
Notify::peerUpdatedDelayed( Notify::peerUpdatedDelayed(
this, this,
(UpdateFlag::RightsChanged (UpdateFlag::RightsChanged
@ -140,10 +140,10 @@ void ChatData::setAdminRights(const MTPChatAdminRights &rights) {
} }
void ChatData::setDefaultRestrictions(const MTPChatBannedRights &rights) { void ChatData::setDefaultRestrictions(const MTPChatBannedRights &rights) {
if (rights.c_chatBannedRights().vflags.v == defaultRestrictions()) { if (rights.c_chatBannedRights().vflags().v == defaultRestrictions()) {
return; return;
} }
_defaultRestrictions.set(rights.c_chatBannedRights().vflags.v); _defaultRestrictions.set(rights.c_chatBannedRights().vflags().v);
Notify::peerUpdatedDelayed(this, UpdateFlag::RightsChanged); Notify::peerUpdatedDelayed(this, UpdateFlag::RightsChanged);
} }
@ -186,19 +186,19 @@ namespace Data {
void ApplyChatUpdate( void ApplyChatUpdate(
not_null<ChatData*> chat, not_null<ChatData*> chat,
const MTPDupdateChatParticipants &update) { const MTPDupdateChatParticipants &update) {
ApplyChatUpdate(chat, update.vparticipants); ApplyChatUpdate(chat, update.vparticipants());
} }
void ApplyChatUpdate( void ApplyChatUpdate(
not_null<ChatData*> chat, not_null<ChatData*> chat,
const MTPDupdateChatParticipantAdd &update) { const MTPDupdateChatParticipantAdd &update) {
if (chat->applyUpdateVersion(update.vversion.v) if (chat->applyUpdateVersion(update.vversion().v)
!= ChatData::UpdateStatus::Good) { != ChatData::UpdateStatus::Good) {
return; return;
} else if (chat->count < 0) { } else if (chat->count < 0) {
return; return;
} }
const auto user = chat->owner().userLoaded(update.vuser_id.v); const auto user = chat->owner().userLoaded(update.vuser_id().v);
if (!user if (!user
|| (!chat->participants.empty() || (!chat->participants.empty()
&& chat->participants.contains(user))) { && chat->participants.contains(user))) {
@ -213,7 +213,7 @@ void ApplyChatUpdate(
chat->botStatus = 0; chat->botStatus = 0;
} else { } else {
chat->participants.emplace(user); chat->participants.emplace(user);
if (update.vinviter_id.v == chat->session().userId()) { if (update.vinviter_id().v == chat->session().userId()) {
chat->invitedByMe.insert(user); chat->invitedByMe.insert(user);
} else { } else {
chat->invitedByMe.remove(user); chat->invitedByMe.remove(user);
@ -234,13 +234,13 @@ void ApplyChatUpdate(
void ApplyChatUpdate( void ApplyChatUpdate(
not_null<ChatData*> chat, not_null<ChatData*> chat,
const MTPDupdateChatParticipantDelete &update) { const MTPDupdateChatParticipantDelete &update) {
if (chat->applyUpdateVersion(update.vversion.v) if (chat->applyUpdateVersion(update.vversion().v)
!= ChatData::UpdateStatus::Good) { != ChatData::UpdateStatus::Good) {
return; return;
} else if (chat->count <= 0) { } else if (chat->count <= 0) {
return; return;
} }
const auto user = chat->owner().userLoaded(update.vuser_id.v); const auto user = chat->owner().userLoaded(update.vuser_id().v);
if (!user if (!user
|| (!chat->participants.empty() || (!chat->participants.empty()
&& !chat->participants.contains(user))) { && !chat->participants.contains(user))) {
@ -278,22 +278,22 @@ void ApplyChatUpdate(
void ApplyChatUpdate( void ApplyChatUpdate(
not_null<ChatData*> chat, not_null<ChatData*> chat,
const MTPDupdateChatParticipantAdmin &update) { const MTPDupdateChatParticipantAdmin &update) {
if (chat->applyUpdateVersion(update.vversion.v) if (chat->applyUpdateVersion(update.vversion().v)
!= ChatData::UpdateStatus::Good) { != ChatData::UpdateStatus::Good) {
return; return;
} }
const auto user = chat->owner().userLoaded(update.vuser_id.v); const auto user = chat->owner().userLoaded(update.vuser_id().v);
if (!user) { if (!user) {
chat->invalidateParticipants(); chat->invalidateParticipants();
return; return;
} }
if (user->isSelf()) { if (user->isSelf()) {
chat->setAdminRights(MTP_chatAdminRights(mtpIsTrue(update.vis_admin) chat->setAdminRights(MTP_chatAdminRights(mtpIsTrue(update.vis_admin())
? MTP_flags(ChatData::DefaultAdminRights()) ? MTP_flags(ChatData::DefaultAdminRights())
: MTP_flags(0))); : MTP_flags(0)));
} }
if (mtpIsTrue(update.vis_admin)) { if (mtpIsTrue(update.vis_admin())) {
if (chat->noParticipantInfo()) { if (chat->noParticipantInfo()) {
chat->session().api().requestFullPeer(chat); chat->session().api().requestFullPeer(chat);
} else { } else {
@ -310,20 +310,20 @@ void ApplyChatUpdate(
void ApplyChatUpdate( void ApplyChatUpdate(
not_null<ChatData*> chat, not_null<ChatData*> chat,
const MTPDupdateChatDefaultBannedRights &update) { const MTPDupdateChatDefaultBannedRights &update) {
if (chat->applyUpdateVersion(update.vversion.v) if (chat->applyUpdateVersion(update.vversion().v)
!= ChatData::UpdateStatus::Good) { != ChatData::UpdateStatus::Good) {
return; return;
} }
chat->setDefaultRestrictions(update.vdefault_banned_rights); chat->setDefaultRestrictions(update.vdefault_banned_rights());
} }
void ApplyChatUpdate(not_null<ChatData*> chat, const MTPDchatFull &update) { void ApplyChatUpdate(not_null<ChatData*> chat, const MTPDchatFull &update) {
ApplyChatUpdate(chat, update.vparticipants); ApplyChatUpdate(chat, update.vparticipants());
if (update.has_bot_info()) { if (const auto info = update.vbot_info()) {
for (const auto &item : update.vbot_info.v) { for (const auto &item : info->v) {
item.match([&](const MTPDbotInfo &data) { item.match([&](const MTPDbotInfo &data) {
const auto userId = data.vuser_id.v; const auto userId = data.vuser_id().v;
if (const auto bot = chat->owner().userLoaded(userId)) { if (const auto bot = chat->owner().userLoaded(userId)) {
bot->setBotInfo(item); bot->setBotInfo(item);
chat->session().api().fullPeerUpdated().notify(bot); chat->session().api().fullPeerUpdated().notify(bot);
@ -331,48 +331,50 @@ void ApplyChatUpdate(not_null<ChatData*> chat, const MTPDchatFull &update) {
}); });
} }
} }
chat->setFullFlags(update.vflags.v); chat->setFullFlags(update.vflags().v);
chat->setUserpicPhoto(update.has_chat_photo() if (const auto photo = update.vchat_photo()) {
? update.vchat_photo chat->setUserpicPhoto(*photo);
: MTPPhoto(MTP_photoEmpty(MTP_long(0)))); } else {
chat->setInviteLink(update.vexported_invite.match([&]( chat->setUserpicPhoto(MTP_photoEmpty(MTP_long(0)));
}
chat->setInviteLink(update.vexported_invite().match([&](
const MTPDchatInviteExported &data) { const MTPDchatInviteExported &data) {
return qs(data.vlink); return qs(data.vlink());
}, [&](const MTPDchatInviteEmpty &) { }, [&](const MTPDchatInviteEmpty &) {
return QString(); return QString();
})); }));
if (update.has_pinned_msg_id()) { if (const auto pinned = update.vpinned_msg_id()) {
chat->setPinnedMessageId(update.vpinned_msg_id.v); chat->setPinnedMessageId(pinned->v);
} else { } else {
chat->clearPinnedMessage(); chat->clearPinnedMessage();
} }
chat->checkFolder(update.has_folder_id() ? update.vfolder_id.v : 0); chat->checkFolder(update.vfolder_id().value_or_empty());
chat->fullUpdated(); chat->fullUpdated();
chat->session().api().applyNotifySettings( chat->session().api().applyNotifySettings(
MTP_inputNotifyPeer(chat->input), MTP_inputNotifyPeer(chat->input),
update.vnotify_settings); update.vnotify_settings());
} }
void ApplyChatUpdate( void ApplyChatUpdate(
not_null<ChatData*> chat, not_null<ChatData*> chat,
const MTPChatParticipants &participants) { const MTPChatParticipants &participants) {
participants.match([&](const MTPDchatParticipantsForbidden &data) { participants.match([&](const MTPDchatParticipantsForbidden &data) {
if (data.has_self_participant()) { if (const auto self = data.vself_participant()) {
// data.vself_participant. // self->
} }
chat->count = -1; chat->count = -1;
chat->invalidateParticipants(); chat->invalidateParticipants();
}, [&](const MTPDchatParticipants &data) { }, [&](const MTPDchatParticipants &data) {
const auto status = chat->applyUpdateVersion(data.vversion.v); const auto status = chat->applyUpdateVersion(data.vversion().v);
if (status == ChatData::UpdateStatus::TooOld) { if (status == ChatData::UpdateStatus::TooOld) {
return; return;
} }
// Even if we skipped some updates, we got current participants // Even if we skipped some updates, we got current participants
// and we've requested peer from API to have current rights. // and we've requested peer from API to have current rights.
chat->setVersion(data.vversion.v); chat->setVersion(data.vversion().v);
const auto &list = data.vparticipants.v; const auto &list = data.vparticipants().v;
chat->count = list.size(); chat->count = list.size();
chat->participants.clear(); chat->participants.clear();
chat->invitedByMe.clear(); chat->invitedByMe.clear();
@ -381,7 +383,7 @@ void ApplyChatUpdate(
const auto selfUserId = chat->session().userId(); const auto selfUserId = chat->session().userId();
for (const auto &participant : list) { for (const auto &participant : list) {
const auto userId = participant.match([&](const auto &data) { const auto userId = participant.match([&](const auto &data) {
return data.vuser_id.v; return data.vuser_id().v;
}); });
const auto user = chat->owner().userLoaded(userId); const auto user = chat->owner().userLoaded(userId);
if (!user) { if (!user) {
@ -395,7 +397,7 @@ void ApplyChatUpdate(
const MTPDchatParticipantCreator &data) { const MTPDchatParticipantCreator &data) {
return 0; return 0;
}, [&](const auto &data) { }, [&](const auto &data) {
return data.vinviter_id.v; return data.vinviter_id().v;
}); });
if (inviterId == selfUserId) { if (inviterId == selfUserId) {
chat->invitedByMe.insert(user); chat->invitedByMe.insert(user);

View file

@ -428,7 +428,7 @@ void DocumentOpenWithClickHandler::onClickImpl() const {
Data::FileOrigin StickerData::setOrigin() const { Data::FileOrigin StickerData::setOrigin() const {
return set.match([&](const MTPDinputStickerSetID &data) { return set.match([&](const MTPDinputStickerSetID &data) {
return Data::FileOrigin( return Data::FileOrigin(
Data::FileOriginStickerSet(data.vid.v, data.vaccess_hash.v)); Data::FileOriginStickerSet(data.vid().v, data.vaccess_hash().v));
}, [&](const auto &) { }, [&](const auto &) {
return Data::FileOrigin(); return Data::FileOrigin();
}); });
@ -466,7 +466,7 @@ void DocumentData::setattributes(
for (const auto &attribute : attributes) { for (const auto &attribute : attributes) {
attribute.match([&](const MTPDdocumentAttributeImageSize &data) { attribute.match([&](const MTPDdocumentAttributeImageSize &data) {
dimensions = QSize(data.vw.v, data.vh.v); dimensions = QSize(data.vw().v, data.vh().v);
}, [&](const MTPDdocumentAttributeAnimated &data) { }, [&](const MTPDdocumentAttributeAnimated &data) {
if (type == FileDocument if (type == FileDocument
|| type == StickerDocument || type == StickerDocument
@ -480,10 +480,10 @@ void DocumentData::setattributes(
_additional = std::make_unique<StickerData>(); _additional = std::make_unique<StickerData>();
} }
if (sticker()) { if (sticker()) {
sticker()->alt = qs(data.valt); sticker()->alt = qs(data.valt());
if (sticker()->set.type() != mtpc_inputStickerSetID if (sticker()->set.type() != mtpc_inputStickerSetID
|| data.vstickerset.type() == mtpc_inputStickerSetID) { || data.vstickerset().type() == mtpc_inputStickerSetID) {
sticker()->set = data.vstickerset; sticker()->set = data.vstickerset();
} }
} }
}, [&](const MTPDdocumentAttributeVideo &data) { }, [&](const MTPDdocumentAttributeVideo &data) {
@ -492,9 +492,9 @@ void DocumentData::setattributes(
? RoundVideoDocument ? RoundVideoDocument
: VideoDocument; : VideoDocument;
} }
_duration = data.vduration.v; _duration = data.vduration().v;
setMaybeSupportsStreaming(data.is_supports_streaming()); setMaybeSupportsStreaming(data.is_supports_streaming());
dimensions = QSize(data.vw.v, data.vh.v); dimensions = QSize(data.vw().v, data.vh().v);
}, [&](const MTPDdocumentAttributeAudio &data) { }, [&](const MTPDdocumentAttributeAudio &data) {
if (type == FileDocument) { if (type == FileDocument) {
if (data.is_voice()) { if (data.is_voice()) {
@ -506,19 +506,19 @@ void DocumentData::setattributes(
} }
} }
if (const auto voiceData = voice()) { if (const auto voiceData = voice()) {
voiceData->duration = data.vduration.v; voiceData->duration = data.vduration().v;
voiceData->waveform = documentWaveformDecode( voiceData->waveform = documentWaveformDecode(
qba(data.vwaveform)); data.vwaveform().value_or_empty());
voiceData->wavemax = voiceData->waveform.empty() voiceData->wavemax = voiceData->waveform.empty()
? uchar(0) ? uchar(0)
: *ranges::max_element(voiceData->waveform); : *ranges::max_element(voiceData->waveform);
} else if (const auto songData = song()) { } else if (const auto songData = song()) {
songData->duration = data.vduration.v; songData->duration = data.vduration().v;
songData->title = qs(data.vtitle); songData->title = qs(data.vtitle().value_or_empty());
songData->performer = qs(data.vperformer); songData->performer = qs(data.vperformer().value_or_empty());
} }
}, [&](const MTPDdocumentAttributeFilename &data) { }, [&](const MTPDdocumentAttributeFilename &data) {
_filename = qs(data.vfile_name); _filename = qs(data.vfile_name());
// We don't want LTR/RTL mark/embedding/override/isolate chars // We don't want LTR/RTL mark/embedding/override/isolate chars
// in filenames, because they introduce a security issue, when // in filenames, because they introduce a security issue, when
@ -684,7 +684,7 @@ auto DocumentData::bigFileBaseCacheKey() const
MTP_long(id), MTP_long(id),
MTP_long(_access), MTP_long(_access),
MTP_bytes(_fileReference), MTP_bytes(_fileReference),
MTP_string(QString()))).bigFileBaseCacheKey(); MTP_string())).bigFileBaseCacheKey();
} }
return std::nullopt; return std::nullopt;
} }
@ -961,7 +961,7 @@ void DocumentData::save(
MTP_long(id), MTP_long(id),
MTP_long(_access), MTP_long(_access),
MTP_bytes(_fileReference), MTP_bytes(_fileReference),
MTP_string(QString()))), MTP_string())),
origin, origin,
locationType(), locationType(),
toFile, toFile,
@ -1119,12 +1119,12 @@ bool DocumentData::isStickerSetInstalled() const {
const auto &sets = _owner->stickerSets(); const auto &sets = _owner->stickerSets();
return sticker()->set.match([&](const MTPDinputStickerSetID &data) { return sticker()->set.match([&](const MTPDinputStickerSetID &data) {
const auto i = sets.constFind(data.vid.v); const auto i = sets.constFind(data.vid().v);
return (i != sets.cend()) return (i != sets.cend())
&& !(i->flags & MTPDstickerSet::Flag::f_archived) && !(i->flags & MTPDstickerSet::Flag::f_archived)
&& (i->flags & MTPDstickerSet::Flag::f_installed_date); && (i->flags & MTPDstickerSet::Flag::f_installed_date);
}, [&](const MTPDinputStickerSetShortName &data) { }, [&](const MTPDinputStickerSetShortName &data) {
const auto name = qs(data.vshort_name).toLower(); const auto name = qs(data.vshort_name()).toLower();
for (const auto &set : sets) { for (const auto &set : sets) {
if (set.shortName.toLower() == name) { if (set.shortName.toLower() == name) {
return !(set.flags & MTPDstickerSet::Flag::f_archived) return !(set.flags & MTPDstickerSet::Flag::f_archived)
@ -1326,7 +1326,7 @@ auto DocumentData::createStreamingLoader(
MTP_long(id), MTP_long(id),
MTP_long(_access), MTP_long(_access),
MTP_bytes(_fileReference), MTP_bytes(_fileReference),
MTP_string(QString()))), MTP_string())),
size, size,
origin) origin)
: nullptr; : nullptr;

View file

@ -47,14 +47,13 @@ Draft::Draft(
void applyPeerCloudDraft(PeerId peerId, const MTPDdraftMessage &draft) { void applyPeerCloudDraft(PeerId peerId, const MTPDdraftMessage &draft) {
const auto history = Auth().data().history(peerId); const auto history = Auth().data().history(peerId);
const auto textWithTags = TextWithTags { const auto textWithTags = TextWithTags {
qs(draft.vmessage), qs(draft.vmessage()),
ConvertEntitiesToTextTags( ConvertEntitiesToTextTags(
draft.has_entities() TextUtilities::EntitiesFromMTP(
? TextUtilities::EntitiesFromMTP(draft.ventities.v) draft.ventities().value_or_empty()))
: EntitiesInText())
}; };
auto replyTo = draft.has_reply_to_msg_id() ? draft.vreply_to_msg_id.v : MsgId(0); auto replyTo = draft.vreply_to_msg_id().value_or_empty();
if (history->skipCloudDraft(textWithTags.text, replyTo, draft.vdate.v)) { if (history->skipCloudDraft(textWithTags.text, replyTo, draft.vdate().v)) {
return; return;
} }
auto cloudDraft = std::make_unique<Draft>( auto cloudDraft = std::make_unique<Draft>(
@ -62,7 +61,7 @@ void applyPeerCloudDraft(PeerId peerId, const MTPDdraftMessage &draft) {
replyTo, replyTo,
MessageCursor(QFIXED_MAX, QFIXED_MAX, QFIXED_MAX), MessageCursor(QFIXED_MAX, QFIXED_MAX, QFIXED_MAX),
draft.is_no_webpage()); draft.is_no_webpage());
cloudDraft->date = draft.vdate.v; cloudDraft->date = draft.vdate().v;
history->setCloudDraft(std::move(cloudDraft)); history->setCloudDraft(std::move(cloudDraft));
history->applyCloudDraft(); history->applyCloudDraft();

View file

@ -20,68 +20,68 @@ struct FileReferenceAccumulator {
void push(const MTPPhoto &data) { void push(const MTPPhoto &data) {
data.match([&](const MTPDphoto &data) { data.match([&](const MTPDphoto &data) {
result.data.emplace( result.data.emplace(
PhotoFileLocationId{ data.vid.v }, PhotoFileLocationId{ data.vid().v },
data.vfile_reference.v); data.vfile_reference().v);
}, [](const MTPDphotoEmpty &data) { }, [](const MTPDphotoEmpty &data) {
}); });
} }
void push(const MTPDocument &data) { void push(const MTPDocument &data) {
data.match([&](const MTPDdocument &data) { data.match([&](const MTPDdocument &data) {
result.data.emplace( result.data.emplace(
DocumentFileLocationId{ data.vid.v }, DocumentFileLocationId{ data.vid().v },
data.vfile_reference.v); data.vfile_reference().v);
}, [](const MTPDdocumentEmpty &data) { }, [](const MTPDdocumentEmpty &data) {
}); });
} }
void push(const MTPWallPaper &data) { void push(const MTPWallPaper &data) {
data.match([&](const MTPDwallPaper &data) { data.match([&](const MTPDwallPaper &data) {
push(data.vdocument); push(data.vdocument());
}); });
} }
void push(const MTPWebPage &data) { void push(const MTPWebPage &data) {
data.match([&](const MTPDwebPage &data) { data.match([&](const MTPDwebPage &data) {
if (data.has_document()) { if (const auto document = data.vdocument()) {
push(data.vdocument); push(*document);
} }
if (data.has_photo()) { if (const auto photo = data.vphoto()) {
push(data.vphoto); push(*photo);
} }
}, [](const auto &data) { }, [](const auto &data) {
}); });
} }
void push(const MTPGame &data) { void push(const MTPGame &data) {
data.match([&](const MTPDgame &data) { data.match([&](const MTPDgame &data) {
if (data.has_document()) { if (const auto document = data.vdocument()) {
push(data.vdocument); push(*document);
} }
}, [](const auto &data) { }, [](const auto &data) {
}); });
} }
void push(const MTPMessageMedia &data) { void push(const MTPMessageMedia &data) {
data.match([&](const MTPDmessageMediaPhoto &data) { data.match([&](const MTPDmessageMediaPhoto &data) {
if (data.has_photo()) { if (const auto photo = data.vphoto()) {
push(data.vphoto); push(*photo);
} }
}, [&](const MTPDmessageMediaDocument &data) { }, [&](const MTPDmessageMediaDocument &data) {
if (data.has_document()) { if (const auto document = data.vdocument()) {
push(data.vdocument); push(*document);
} }
}, [&](const MTPDmessageMediaWebPage &data) { }, [&](const MTPDmessageMediaWebPage &data) {
push(data.vwebpage); push(data.vwebpage());
}, [&](const MTPDmessageMediaGame &data) { }, [&](const MTPDmessageMediaGame &data) {
push(data.vgame); push(data.vgame());
}, [](const auto &data) { }, [](const auto &data) {
}); });
} }
void push(const MTPMessage &data) { void push(const MTPMessage &data) {
data.match([&](const MTPDmessage &data) { data.match([&](const MTPDmessage &data) {
if (data.has_media()) { if (const auto media = data.vmedia()) {
push(data.vmedia); push(*media);
} }
}, [&](const MTPDmessageService &data) { }, [&](const MTPDmessageService &data) {
data.vaction.match( data.vaction().match(
[&](const MTPDmessageActionChatEditPhoto &data) { [&](const MTPDmessageActionChatEditPhoto &data) {
push(data.vphoto); push(data.vphoto());
}, [](const auto &data) { }, [](const auto &data) {
}); });
}, [](const MTPDmessageEmpty &data) { }, [](const MTPDmessageEmpty &data) {
@ -90,34 +90,34 @@ struct FileReferenceAccumulator {
void push(const MTPmessages_Messages &data) { void push(const MTPmessages_Messages &data) {
data.match([](const MTPDmessages_messagesNotModified &) { data.match([](const MTPDmessages_messagesNotModified &) {
}, [&](const auto &data) { }, [&](const auto &data) {
push(data.vmessages); push(data.vmessages());
}); });
} }
void push(const MTPphotos_Photos &data) { void push(const MTPphotos_Photos &data) {
data.match([&](const auto &data) { data.match([&](const auto &data) {
push(data.vphotos); push(data.vphotos());
}); });
} }
void push(const MTPmessages_RecentStickers &data) { void push(const MTPmessages_RecentStickers &data) {
data.match([&](const MTPDmessages_recentStickers &data) { data.match([&](const MTPDmessages_recentStickers &data) {
push(data.vstickers); push(data.vstickers());
}, [](const MTPDmessages_recentStickersNotModified &data) { }, [](const MTPDmessages_recentStickersNotModified &data) {
}); });
} }
void push(const MTPmessages_FavedStickers &data) { void push(const MTPmessages_FavedStickers &data) {
data.match([&](const MTPDmessages_favedStickers &data) { data.match([&](const MTPDmessages_favedStickers &data) {
push(data.vstickers); push(data.vstickers());
}, [](const MTPDmessages_favedStickersNotModified &data) { }, [](const MTPDmessages_favedStickersNotModified &data) {
}); });
} }
void push(const MTPmessages_StickerSet &data) { void push(const MTPmessages_StickerSet &data) {
data.match([&](const MTPDmessages_stickerSet &data) { data.match([&](const MTPDmessages_stickerSet &data) {
push(data.vdocuments); push(data.vdocuments());
}); });
} }
void push(const MTPmessages_SavedGifs &data) { void push(const MTPmessages_SavedGifs &data) {
data.match([&](const MTPDmessages_savedGifs &data) { data.match([&](const MTPDmessages_savedGifs &data) {
push(data.vgifs); push(data.vgifs());
}, [](const MTPDmessages_savedGifsNotModified &data) { }, [](const MTPDmessages_savedGifsNotModified &data) {
}); });
} }

View file

@ -45,9 +45,9 @@ rpl::producer<int> PinnedDialogsInFolderMaxValue() {
// Expects(position.type() == mtpc_feedPosition); // Expects(position.type() == mtpc_feedPosition);
// //
// const auto &data = position.c_feedPosition(); // const auto &data = position.c_feedPosition();
// return MessagePosition(data.vdate.v, FullMsgId( // return MessagePosition(data.vdate().v, FullMsgId(
// peerToChannel(peerFromMTP(data.vpeer)), // peerToChannel(peerFromMTP(data.vpeer())),
// data.vid.v)); // data.vid().v));
//} //}
Folder::Folder(not_null<Data::Session*> owner, FolderId id) Folder::Folder(not_null<Data::Session*> owner, FolderId id)
@ -330,11 +330,11 @@ TimeId Folder::adjustedChatListTimeId() const {
void Folder::applyDialog(const MTPDdialogFolder &data) { void Folder::applyDialog(const MTPDdialogFolder &data) {
updateCloudUnread(data); updateCloudUnread(data);
if (const auto peerId = peerFromMTP(data.vpeer)) { if (const auto peerId = peerFromMTP(data.vpeer())) {
const auto history = owner().history(peerId); const auto history = owner().history(peerId);
const auto fullId = FullMsgId( const auto fullId = FullMsgId(
peerToChannel(peerId), peerToChannel(peerId),
data.vtop_message.v); data.vtop_message().v);
history->setFolder(this, owner().message(fullId)); history->setFolder(this, owner().message(fullId));
} else { } else {
_chatsList.clear(); _chatsList.clear();
@ -348,10 +348,10 @@ void Folder::applyDialog(const MTPDdialogFolder &data) {
void Folder::updateCloudUnread(const MTPDdialogFolder &data) { void Folder::updateCloudUnread(const MTPDdialogFolder &data) {
const auto notifier = unreadStateChangeNotifier(!_chatsList.loaded()); const auto notifier = unreadStateChangeNotifier(!_chatsList.loaded());
_cloudUnread.messages = data.vunread_muted_messages_count.v _cloudUnread.messages = data.vunread_muted_messages_count().v
+ data.vunread_unmuted_messages_count.v; + data.vunread_unmuted_messages_count().v;
_cloudUnread.chats = data.vunread_muted_peers_count.v _cloudUnread.chats = data.vunread_muted_peers_count().v
+ data.vunread_unmuted_peers_count.v; + data.vunread_unmuted_peers_count().v;
finalizeCloudUnread(); finalizeCloudUnread();
_cloudUnread.known = true; _cloudUnread.known = true;
@ -379,7 +379,7 @@ Dialogs::UnreadState Folder::chatListUnreadState() const {
} }
void Folder::applyPinnedUpdate(const MTPDupdateDialogPinned &data) { void Folder::applyPinnedUpdate(const MTPDupdateDialogPinned &data) {
const auto folderId = data.has_folder_id() ? data.vfolder_id.v : 0; const auto folderId = data.vfolder_id().value_or_empty();
if (folderId != 0) { if (folderId != 0) {
LOG(("API Error: Nested folders detected.")); LOG(("API Error: Nested folders detected."));
} }

View file

@ -15,9 +15,9 @@ class LocationPoint {
public: public:
LocationPoint() = default; LocationPoint() = default;
explicit LocationPoint(const MTPDgeoPoint &point) explicit LocationPoint(const MTPDgeoPoint &point)
: _lat(point.vlat.v) : _lat(point.vlat().v)
, _lon(point.vlong.v) , _lon(point.vlong().v)
, _access(point.vaccess_hash.v) { , _access(point.vaccess_hash().v) {
} }
QString latAsString() const { QString latAsString() const {

View file

@ -46,8 +46,8 @@ namespace {
Call ComputeCallData(const MTPDmessageActionPhoneCall &call) { Call ComputeCallData(const MTPDmessageActionPhoneCall &call) {
auto result = Call(); auto result = Call();
result.finishReason = [&] { result.finishReason = [&] {
if (call.has_reason()) { if (const auto reason = call.vreason()) {
switch (call.vreason.type()) { switch (reason->type()) {
case mtpc_phoneCallDiscardReasonBusy: case mtpc_phoneCallDiscardReasonBusy:
return CallFinishReason::Busy; return CallFinishReason::Busy;
case mtpc_phoneCallDiscardReasonDisconnect: case mtpc_phoneCallDiscardReasonDisconnect:
@ -61,7 +61,7 @@ Call ComputeCallData(const MTPDmessageActionPhoneCall &call) {
} }
return CallFinishReason::Hangup; return CallFinishReason::Hangup;
}(); }();
result.duration = call.has_duration() ? call.vduration.v : 0;; result.duration = call.vduration().value_or_empty();
return result; return result;
} }
@ -70,15 +70,13 @@ Invoice ComputeInvoiceData(
const MTPDmessageMediaInvoice &data) { const MTPDmessageMediaInvoice &data) {
auto result = Invoice(); auto result = Invoice();
result.isTest = data.is_test(); result.isTest = data.is_test();
result.amount = data.vtotal_amount.v; result.amount = data.vtotal_amount().v;
result.currency = qs(data.vcurrency); result.currency = qs(data.vcurrency());
result.description = qs(data.vdescription); result.description = qs(data.vdescription());
result.title = TextUtilities::SingleLine(qs(data.vtitle)); result.title = TextUtilities::SingleLine(qs(data.vtitle()));
if (data.has_receipt_msg_id()) { result.receiptMsgId = data.vreceipt_msg_id().value_or_empty();
result.receiptMsgId = data.vreceipt_msg_id.v; if (const auto photo = data.vphoto()) {
} result.photo = item->history()->owner().photoFromWeb(*photo);
if (data.has_photo()) {
result.photo = item->history()->owner().photoFromWeb(data.vphoto);
} }
return result; return result;
} }
@ -346,10 +344,11 @@ bool MediaPhoto::updateInlineResultMedia(const MTPMessageMedia &media) {
if (media.type() != mtpc_messageMediaPhoto) { if (media.type() != mtpc_messageMediaPhoto) {
return false; return false;
} }
auto &data = media.c_messageMediaPhoto(); const auto &data = media.c_messageMediaPhoto();
if (data.has_photo() && !data.has_ttl_seconds()) { const auto content = data.vphoto();
if (content && !data.vttl_seconds()) {
const auto photo = parent()->history()->owner().processPhoto( const auto photo = parent()->history()->owner().processPhoto(
data.vphoto); *content);
if (photo == _photo) { if (photo == _photo) {
return true; return true;
} else { } else {
@ -367,22 +366,23 @@ bool MediaPhoto::updateSentMedia(const MTPMessageMedia &media) {
if (media.type() != mtpc_messageMediaPhoto) { if (media.type() != mtpc_messageMediaPhoto) {
return false; return false;
} }
auto &mediaPhoto = media.c_messageMediaPhoto(); const auto &mediaPhoto = media.c_messageMediaPhoto();
if (!mediaPhoto.has_photo() || mediaPhoto.has_ttl_seconds()) { const auto content = mediaPhoto.vphoto();
if (!content || mediaPhoto.vttl_seconds()) {
LOG(("Api Error: " LOG(("Api Error: "
"Got MTPMessageMediaPhoto without photo " "Got MTPMessageMediaPhoto without photo "
"or with ttl_seconds in updateSentMedia()")); "or with ttl_seconds in updateSentMedia()"));
return false; return false;
} }
parent()->history()->owner().photoConvert(_photo, mediaPhoto.vphoto); parent()->history()->owner().photoConvert(_photo, *content);
if (mediaPhoto.vphoto.type() != mtpc_photo) { if (content->type() != mtpc_photo) {
return false; return false;
} }
const auto &photo = mediaPhoto.vphoto.c_photo(); const auto &photo = content->c_photo();
struct SizeData { struct SizeData {
MTPstring type = MTP_string(QString()); MTPstring type = MTP_string();
int width = 0; int width = 0;
int height = 0; int height = 0;
QByteArray bytes; QByteArray bytes;
@ -394,12 +394,12 @@ bool MediaPhoto::updateSentMedia(const MTPMessageMedia &media) {
const auto key = StorageImageLocation( const auto key = StorageImageLocation(
StorageFileLocation( StorageFileLocation(
photo.vdc_id.v, photo.vdc_id().v,
_photo->session().userId(), _photo->session().userId(),
MTP_inputPhotoFileLocation( MTP_inputPhotoFileLocation(
photo.vid, photo.vid(),
photo.vaccess_hash, photo.vaccess_hash(),
photo.vfile_reference, photo.vfile_reference(),
size.type)), size.type)),
size.width, size.width,
size.height); size.height);
@ -422,23 +422,23 @@ bool MediaPhoto::updateSentMedia(const MTPMessageMedia &media) {
image->replaceSource( image->replaceSource(
std::make_unique<Images::StorageSource>(key, length)); std::make_unique<Images::StorageSource>(key, length));
}; };
auto &sizes = photo.vsizes.v; auto &sizes = photo.vsizes().v;
auto max = 0; auto max = 0;
auto maxSize = SizeData(); auto maxSize = SizeData();
for (const auto &data : sizes) { for (const auto &data : sizes) {
const auto size = data.match([](const MTPDphotoSize &data) { const auto size = data.match([](const MTPDphotoSize &data) {
return SizeData{ return SizeData{
data.vtype, data.vtype(),
data.vw.v, data.vw().v,
data.vh.v, data.vh().v,
QByteArray() QByteArray()
}; };
}, [](const MTPDphotoCachedSize &data) { }, [](const MTPDphotoCachedSize &data) {
return SizeData{ return SizeData{
data.vtype, data.vtype(),
data.vw.v, data.vw().v,
data.vh.v, data.vh().v,
qba(data.vbytes) qba(data.vbytes())
}; };
}, [](const MTPDphotoSizeEmpty &) { }, [](const MTPDphotoSizeEmpty &) {
return SizeData(); return SizeData();
@ -708,10 +708,11 @@ bool MediaFile::updateInlineResultMedia(const MTPMessageMedia &media) {
if (media.type() != mtpc_messageMediaDocument) { if (media.type() != mtpc_messageMediaDocument) {
return false; return false;
} }
auto &data = media.c_messageMediaDocument(); const auto &data = media.c_messageMediaDocument();
if (data.has_document() && !data.has_ttl_seconds()) { const auto content = data.vdocument();
if (content && !data.vttl_seconds()) {
const auto document = parent()->history()->owner().processDocument( const auto document = parent()->history()->owner().processDocument(
data.vdocument); *content);
if (document == _document) { if (document == _document) {
return false; return false;
} else { } else {
@ -729,14 +730,15 @@ bool MediaFile::updateSentMedia(const MTPMessageMedia &media) {
if (media.type() != mtpc_messageMediaDocument) { if (media.type() != mtpc_messageMediaDocument) {
return false; return false;
} }
auto &data = media.c_messageMediaDocument(); const auto &data = media.c_messageMediaDocument();
if (!data.has_document() || data.has_ttl_seconds()) { const auto content = data.vdocument();
if (!content || data.vttl_seconds()) {
LOG(("Api Error: " LOG(("Api Error: "
"Got MTPMessageMediaDocument without document " "Got MTPMessageMediaDocument without document "
"or with ttl_seconds in updateSentMedia()")); "or with ttl_seconds in updateSentMedia()"));
return false; return false;
} }
parent()->history()->owner().documentConvert(_document, data.vdocument); parent()->history()->owner().documentConvert(_document, *content);
if (const auto good = _document->goodThumbnail()) { if (const auto good = _document->goodThumbnail()) {
auto bytes = good->bytesForCache(); auto bytes = good->bytesForCache();
@ -836,11 +838,11 @@ bool MediaContact::updateSentMedia(const MTPMessageMedia &media) {
if (media.type() != mtpc_messageMediaContact) { if (media.type() != mtpc_messageMediaContact) {
return false; return false;
} }
if (_contact.userId != media.c_messageMediaContact().vuser_id.v) { if (_contact.userId != media.c_messageMediaContact().vuser_id().v) {
parent()->history()->owner().unregisterContactItem( parent()->history()->owner().unregisterContactItem(
_contact.userId, _contact.userId,
parent()); parent());
_contact.userId = media.c_messageMediaContact().vuser_id.v; _contact.userId = media.c_messageMediaContact().vuser_id().v;
parent()->history()->owner().registerContactItem( parent()->history()->owner().registerContactItem(
_contact.userId, _contact.userId,
parent()); parent());
@ -1168,7 +1170,7 @@ bool MediaGame::updateSentMedia(const MTPMessageMedia &media) {
return false; return false;
} }
parent()->history()->owner().gameConvert( parent()->history()->owner().gameConvert(
_game, media.c_messageMediaGame().vgame); _game, media.c_messageMediaGame().vgame());
return true; return true;
} }

View file

@ -55,15 +55,17 @@ NotifySettingsValue::NotifySettingsValue(
} }
bool NotifySettingsValue::change(const MTPDpeerNotifySettings &data) { bool NotifySettingsValue::change(const MTPDpeerNotifySettings &data) {
return change(data.has_mute_until() const auto mute = data.vmute_until();
? base::make_optional(data.vmute_until.v) const auto sound = data.vsound();
: std::nullopt, data.has_sound() const auto showPreviews = data.vshow_previews();
? base::make_optional(qs(data.vsound)) const auto silent = data.vsilent();
: std::nullopt, data.has_show_previews() return change(
? base::make_optional(mtpIsTrue(data.vshow_previews)) mute ? std::make_optional(mute->v) : std::nullopt,
: std::nullopt, data.has_silent() sound ? std::make_optional(qs(*sound)) : std::nullopt,
? base::make_optional(mtpIsTrue(data.vsilent)) (showPreviews
: std::nullopt); ? std::make_optional(mtpIsTrue(*showPreviews))
: std::nullopt),
silent ? std::make_optional(mtpIsTrue(*silent)) : std::nullopt);
} }
bool NotifySettingsValue::change( bool NotifySettingsValue::change(
@ -139,7 +141,7 @@ bool NotifySettings::change(const MTPPeerNotifySettings &settings) {
Expects(settings.type() == mtpc_peerNotifySettings); Expects(settings.type() == mtpc_peerNotifySettings);
auto &data = settings.c_peerNotifySettings(); auto &data = settings.c_peerNotifySettings();
const auto empty = !data.vflags.v; const auto empty = !data.vflags().v;
if (empty) { if (empty) {
if (!_known || _value) { if (!_known || _value) {
_known = true; _known = true;

View file

@ -327,8 +327,8 @@ void PeerData::updateUserpic(
MTP_inputPeerPhotoFileLocation( MTP_inputPeerPhotoFileLocation(
MTP_flags(0), MTP_flags(0),
input, input,
deprecated.vvolume_id, deprecated.vvolume_id(),
deprecated.vlocal_id)), deprecated.vlocal_id())),
size, size,
size); size);
}); });

View file

@ -38,17 +38,17 @@ PollData::PollData(PollId id) : id(id) {
} }
bool PollData::applyChanges(const MTPDpoll &poll) { bool PollData::applyChanges(const MTPDpoll &poll) {
Expects(poll.vid.v == id); Expects(poll.vid().v == id);
const auto newQuestion = qs(poll.vquestion); const auto newQuestion = qs(poll.vquestion());
const auto newClosed = poll.is_closed(); const auto newClosed = poll.is_closed();
auto newAnswers = ranges::view::all( auto newAnswers = ranges::view::all(
poll.vanswers.v poll.vanswers().v
) | ranges::view::transform([](const MTPPollAnswer &data) { ) | ranges::view::transform([](const MTPPollAnswer &data) {
return data.match([](const MTPDpollAnswer &answer) { return data.match([](const MTPDpollAnswer &answer) {
auto result = PollAnswer(); auto result = PollAnswer();
result.option = answer.voption.v; result.option = answer.voption().v;
result.text = qs(answer.vtext); result.text = qs(answer.vtext());
return result; return result;
}); });
}) | ranges::view::take( }) | ranges::view::take(
@ -82,12 +82,11 @@ bool PollData::applyResults(const MTPPollResults &results) {
return results.match([&](const MTPDpollResults &results) { return results.match([&](const MTPDpollResults &results) {
lastResultsUpdate = crl::now(); lastResultsUpdate = crl::now();
const auto newTotalVoters = results.has_total_voters() const auto newTotalVoters =
? results.vtotal_voters.v results.vtotal_voters().value_or(totalVoters);
: totalVoters;
auto changed = (newTotalVoters != totalVoters); auto changed = (newTotalVoters != totalVoters);
if (results.has_results()) { if (const auto list = results.vresults()) {
for (const auto &result : results.vresults.v) { for (const auto &result : list->v) {
if (applyResultToAnswers(result, results.is_min())) { if (applyResultToAnswers(result, results.is_min())) {
changed = true; changed = true;
} }
@ -124,14 +123,14 @@ bool PollData::applyResultToAnswers(
const MTPPollAnswerVoters &result, const MTPPollAnswerVoters &result,
bool isMinResults) { bool isMinResults) {
return result.match([&](const MTPDpollAnswerVoters &voters) { return result.match([&](const MTPDpollAnswerVoters &voters) {
const auto &option = voters.voption.v; const auto &option = voters.voption().v;
const auto answer = answerByOption(option); const auto answer = answerByOption(option);
if (!answer) { if (!answer) {
return false; return false;
} }
auto changed = (answer->votes != voters.vvoters.v); auto changed = (answer->votes != voters.vvoters().v);
if (changed) { if (changed) {
answer->votes = voters.vvoters.v; answer->votes = voters.vvoters().v;
} }
if (!isMinResults) { if (!isMinResults) {
if (answer->chosen != voters.is_chosen()) { if (answer->chosen != voters.is_chosen()) {

View file

@ -22,7 +22,7 @@ constexpr auto kDefaultSearchTimeoutMs = crl::time(200);
} // namespace } // namespace
MTPmessages_Search PrepareSearchRequest( std::optional<MTPmessages_Search> PrepareSearchRequest(
not_null<PeerData*> peer, not_null<PeerData*> peer,
Storage::SharedMediaType type, Storage::SharedMediaType type,
const QString &query, const QString &query,
@ -56,6 +56,9 @@ MTPmessages_Search PrepareSearchRequest(
} }
return MTP_inputMessagesFilterEmpty(); return MTP_inputMessagesFilterEmpty();
}(); }();
if (query.isEmpty() && filter.type() == mtpc_inputMessagesFilterEmpty) {
return std::nullopt;
}
const auto minId = 0; const auto minId = 0;
const auto maxId = 0; const auto maxId = 0;
@ -107,32 +110,32 @@ SearchResult ParseSearchResult(
switch (data.type()) { switch (data.type()) {
case mtpc_messages_messages: { case mtpc_messages_messages: {
auto &d = data.c_messages_messages(); auto &d = data.c_messages_messages();
peer->owner().processUsers(d.vusers); peer->owner().processUsers(d.vusers());
peer->owner().processChats(d.vchats); peer->owner().processChats(d.vchats());
result.fullCount = d.vmessages.v.size(); result.fullCount = d.vmessages().v.size();
return &d.vmessages.v; return &d.vmessages().v;
} break; } break;
case mtpc_messages_messagesSlice: { case mtpc_messages_messagesSlice: {
auto &d = data.c_messages_messagesSlice(); auto &d = data.c_messages_messagesSlice();
peer->owner().processUsers(d.vusers); peer->owner().processUsers(d.vusers());
peer->owner().processChats(d.vchats); peer->owner().processChats(d.vchats());
result.fullCount = d.vcount.v; result.fullCount = d.vcount().v;
return &d.vmessages.v; return &d.vmessages().v;
} break; } break;
case mtpc_messages_channelMessages: { case mtpc_messages_channelMessages: {
auto &d = data.c_messages_channelMessages(); auto &d = data.c_messages_channelMessages();
if (auto channel = peer->asChannel()) { if (auto channel = peer->asChannel()) {
channel->ptsReceived(d.vpts.v); channel->ptsReceived(d.vpts().v);
} else { } else {
LOG(("API Error: received messages.channelMessages when " LOG(("API Error: received messages.channelMessages when "
"no channel was passed! (ParseSearchResult)")); "no channel was passed! (ParseSearchResult)"));
} }
peer->owner().processUsers(d.vusers); peer->owner().processUsers(d.vusers());
peer->owner().processChats(d.vchats); peer->owner().processChats(d.vchats());
result.fullCount = d.vcount.v; result.fullCount = d.vcount().v;
return &d.vmessages.v; return &d.vmessages().v;
} break; } break;
case mtpc_messages_messagesNotModified: { case mtpc_messages_messagesNotModified: {
@ -345,12 +348,17 @@ void SearchController::requestMore(
if (listData->requests.contains(key)) { if (listData->requests.contains(key)) {
return; return;
} }
auto requestId = request(PrepareSearchRequest( auto prepared = PrepareSearchRequest(
listData->peer, listData->peer,
query.type, query.type,
query.query, query.query,
key.aroundId, key.aroundId,
key.direction) key.direction);
if (!prepared) {
return;
}
auto requestId = request(
std::move(*prepared)
).done([=](const MTPmessages_Messages &result) { ).done([=](const MTPmessages_Messages &result) {
listData->requests.remove(key); listData->requests.remove(key);
auto parsed = ParseSearchResult( auto parsed = ParseSearchResult(

View file

@ -26,7 +26,7 @@ struct SearchResult {
int fullCount = 0; int fullCount = 0;
}; };
MTPmessages_Search PrepareSearchRequest( std::optional<MTPmessages_Search> PrepareSearchRequest(
not_null<PeerData*> peer, not_null<PeerData*> peer,
Storage::SharedMediaType type, Storage::SharedMediaType type,
const QString &query, const QString &query,

View file

@ -117,14 +117,18 @@ QString ExtractUnavailableReason(const QString &restriction) {
} }
MTPPhotoSize FindDocumentInlineThumbnail(const MTPDdocument &data) { MTPPhotoSize FindDocumentInlineThumbnail(const MTPDdocument &data) {
const auto &thumbs = data.vthumbs.v; const auto thumbs = data.vthumbs();
if (!thumbs) {
return MTP_photoSizeEmpty(MTP_string());
}
const auto &list = thumbs->v;
const auto i = ranges::find( const auto i = ranges::find(
thumbs, list,
mtpc_photoStrippedSize, mtpc_photoStrippedSize,
&MTPPhotoSize::type); &MTPPhotoSize::type);
return (i != thumbs.end()) return (i != list.end())
? (*i) ? (*i)
: MTPPhotoSize(MTP_photoSizeEmpty(MTP_string(""))); : MTPPhotoSize(MTP_photoSizeEmpty(MTP_string()));
} }
MTPPhotoSize FindDocumentThumbnail(const MTPDdocument &data) { MTPPhotoSize FindDocumentThumbnail(const MTPDdocument &data) {
@ -135,14 +139,18 @@ MTPPhotoSize FindDocumentThumbnail(const MTPDdocument &data) {
}, [](const MTPDphotoStrippedSize &) { }, [](const MTPDphotoStrippedSize &) {
return kInvalid; return kInvalid;
}, [](const auto &data) { }, [](const auto &data) {
return (data.vw.v * data.vh.v); return (data.vw().v * data.vh().v);
}); });
}; };
const auto &thumbs = data.vthumbs.v; const auto thumbs = data.vthumbs();
const auto i = ranges::max_element(thumbs, std::less<>(), area); if (!thumbs) {
return (i != thumbs.end() && area(*i) > 0) return MTP_photoSizeEmpty(MTP_string());
}
const auto &list = thumbs->v;
const auto i = ranges::max_element(list, std::less<>(), area);
return (i != list.end() && area(*i) > 0)
? (*i) ? (*i)
: MTPPhotoSize(MTP_photoSizeEmpty(MTP_string(""))); : MTPPhotoSize(MTP_photoSizeEmpty(MTP_string()));
} }
rpl::producer<int> PinnedDialogsCountMaxValue() { rpl::producer<int> PinnedDialogsCountMaxValue() {
@ -285,7 +293,7 @@ ChannelData *Session::channelLoaded(ChannelId id) const {
not_null<UserData*> Session::processUser(const MTPUser &data) { not_null<UserData*> Session::processUser(const MTPUser &data) {
const auto result = user(data.match([](const auto &data) { const auto result = user(data.match([](const auto &data) {
return data.vid.v; return data.vid().v;
})); }));
auto minimal = false; auto minimal = false;
const MTPUserStatus *status = nullptr; const MTPUserStatus *status = nullptr;
@ -296,8 +304,8 @@ not_null<UserData*> Session::processUser(const MTPUser &data) {
data.match([&](const MTPDuserEmpty &data) { data.match([&](const MTPDuserEmpty &data) {
const auto canShareThisContact = result->canShareThisContactFast(); const auto canShareThisContact = result->canShareThisContactFast();
result->input = MTP_inputPeerUser(data.vid, MTP_long(0)); result->input = MTP_inputPeerUser(data.vid(), MTP_long(0));
result->inputUser = MTP_inputUser(data.vid, MTP_long(0)); result->inputUser = MTP_inputUser(data.vid(), MTP_long(0));
result->setName(tr::lng_deleted(tr::now), QString(), QString(), QString()); result->setName(tr::lng_deleted(tr::now), QString(), QString(), QString());
result->setPhoto(MTP_userProfilePhotoEmpty()); result->setPhoto(MTP_userProfilePhotoEmpty());
//result->setFlags(MTPDuser_ClientFlag::f_inaccessible | 0); //result->setFlags(MTPDuser_ClientFlag::f_inaccessible | 0);
@ -320,22 +328,25 @@ not_null<UserData*> Session::processUser(const MTPUser &data) {
const auto mask = 0 const auto mask = 0
//| MTPDuser_ClientFlag::f_inaccessible //| MTPDuser_ClientFlag::f_inaccessible
| MTPDuser::Flag::f_deleted; | MTPDuser::Flag::f_deleted;
result->setFlags((result->flags() & ~mask) | (data.vflags.v & mask)); result->setFlags((result->flags() & ~mask) | (data.vflags().v & mask));
} else { } else {
result->setFlags(data.vflags.v); result->setFlags(data.vflags().v);
if (data.is_self()) { if (data.is_self()) {
result->input = MTP_inputPeerSelf(); result->input = MTP_inputPeerSelf();
result->inputUser = MTP_inputUserSelf(); result->inputUser = MTP_inputUserSelf();
} else if (!data.has_access_hash()) { } else if (const auto accessHash = data.vaccess_hash()) {
result->input = MTP_inputPeerUser(data.vid, MTP_long(result->accessHash())); result->input = MTP_inputPeerUser(data.vid(), *accessHash);
result->inputUser = MTP_inputUser(data.vid, MTP_long(result->accessHash())); result->inputUser = MTP_inputUser(data.vid(), *accessHash);
} else { } else {
result->input = MTP_inputPeerUser(data.vid, data.vaccess_hash); result->input = MTP_inputPeerUser(data.vid(), MTP_long(result->accessHash()));
result->inputUser = MTP_inputUser(data.vid, data.vaccess_hash); result->inputUser = MTP_inputUser(data.vid(), MTP_long(result->accessHash()));
}
if (const auto restriction = data.vrestriction_reason()) {
result->setUnavailableReason(
ExtractUnavailableReason(qs(*restriction)));
} else {
result->setUnavailableReason(QString());
} }
result->setUnavailableReason(data.is_restricted()
? ExtractUnavailableReason(qs(data.vrestriction_reason))
: QString());
} }
if (data.is_deleted()) { if (data.is_deleted()) {
if (!result->phone().isEmpty()) { if (!result->phone().isEmpty()) {
@ -349,11 +360,11 @@ not_null<UserData*> Session::processUser(const MTPUser &data) {
// apply first_name and last_name from minimal user only if we don't have // 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 // local values for first name and last name already, otherwise skip
bool noLocalName = result->firstName.isEmpty() && result->lastName.isEmpty(); bool noLocalName = result->firstName.isEmpty() && result->lastName.isEmpty();
QString fname = (!minimal || noLocalName) ? (data.has_first_name() ? TextUtilities::SingleLine(qs(data.vfirst_name)) : QString()) : result->firstName; QString fname = (!minimal || noLocalName) ? TextUtilities::SingleLine(qs(data.vfirst_name().value_or_empty())) : result->firstName;
QString lname = (!minimal || noLocalName) ? (data.has_last_name() ? TextUtilities::SingleLine(qs(data.vlast_name)) : QString()) : result->lastName; QString lname = (!minimal || noLocalName) ? TextUtilities::SingleLine(qs(data.vlast_name().value_or_empty())) : result->lastName;
QString phone = minimal ? result->phone() : (data.has_phone() ? qs(data.vphone) : QString()); QString phone = minimal ? result->phone() : qs(data.vphone().value_or_empty());
QString uname = minimal ? result->username : (data.has_username() ? TextUtilities::SingleLine(qs(data.vusername)) : QString()); QString uname = minimal ? result->username : TextUtilities::SingleLine(qs(data.vusername().value_or_empty()));
const auto phoneChanged = (result->phone() != phone); const auto phoneChanged = (result->phone() != phone);
if (phoneChanged) { if (phoneChanged) {
@ -394,25 +405,29 @@ not_null<UserData*> Session::processUser(const MTPUser &data) {
CrashReports::SetAnnotation("Username", uname); CrashReports::SetAnnotation("Username", uname);
} }
result->setName(fname, lname, pname, uname); result->setName(fname, lname, pname, uname);
if (data.has_photo()) { if (const auto photo = data.vphoto()) {
result->setPhoto(data.vphoto); result->setPhoto(*photo);
} else { } else {
result->setPhoto(MTP_userProfilePhotoEmpty()); result->setPhoto(MTP_userProfilePhotoEmpty());
} }
if (data.has_access_hash()) { if (const auto accessHash = data.vaccess_hash()) {
result->setAccessHash(data.vaccess_hash.v); result->setAccessHash(accessHash->v);
} }
status = data.has_status() ? &data.vstatus : &emptyStatus; status = data.vstatus();
} }
if (!minimal) { if (!minimal) {
if (data.has_bot_info_version()) { if (const auto botInfoVersion = data.vbot_info_version()) {
result->setBotInfoVersion(data.vbot_info_version.v); result->setBotInfoVersion(botInfoVersion->v);
result->botInfo->readsAllHistory = data.is_bot_chat_history(); result->botInfo->readsAllHistory = data.is_bot_chat_history();
if (result->botInfo->cantJoinGroups != data.is_bot_nochats()) { if (result->botInfo->cantJoinGroups != data.is_bot_nochats()) {
result->botInfo->cantJoinGroups = data.is_bot_nochats(); result->botInfo->cantJoinGroups = data.is_bot_nochats();
update.flags |= UpdateFlag::BotCanAddToGroups; update.flags |= UpdateFlag::BotCanAddToGroups;
} }
result->botInfo->inlinePlaceholder = data.has_bot_inline_placeholder() ? '_' + qs(data.vbot_inline_placeholder) : QString(); if (const auto placeholder = data.vbot_inline_placeholder()) {
result->botInfo->inlinePlaceholder = '_' + qs(*placeholder);
} else {
result->botInfo->inlinePlaceholder = QString();
}
} else { } else {
result->setBotInfoVersion(-1); result->setBotInfoVersion(-1);
} }
@ -456,15 +471,15 @@ not_null<UserData*> Session::processUser(const MTPUser &data) {
not_null<PeerData*> Session::processChat(const MTPChat &data) { not_null<PeerData*> Session::processChat(const MTPChat &data) {
const auto result = data.match([&](const MTPDchat &data) { const auto result = data.match([&](const MTPDchat &data) {
return peer(peerFromChat(data.vid.v)); return peer(peerFromChat(data.vid().v));
}, [&](const MTPDchatForbidden &data) { }, [&](const MTPDchatForbidden &data) {
return peer(peerFromChat(data.vid.v)); return peer(peerFromChat(data.vid().v));
}, [&](const MTPDchatEmpty &data) { }, [&](const MTPDchatEmpty &data) {
return peer(peerFromChat(data.vid.v)); return peer(peerFromChat(data.vid().v));
}, [&](const MTPDchannel &data) { }, [&](const MTPDchannel &data) {
return peer(peerFromChannel(data.vid.v)); return peer(peerFromChannel(data.vid().v));
}, [&](const MTPDchannelForbidden &data) { }, [&](const MTPDchannelForbidden &data) {
return peer(peerFromChannel(data.vid.v)); return peer(peerFromChannel(data.vid().v));
}); });
auto minimal = false; auto minimal = false;
@ -475,45 +490,49 @@ not_null<PeerData*> Session::processChat(const MTPChat &data) {
const auto chat = result->asChat(); const auto chat = result->asChat();
const auto canAddMembers = chat->canAddMembers(); const auto canAddMembers = chat->canAddMembers();
if (chat->version() < data.vversion.v) { if (chat->version() < data.vversion().v) {
chat->setVersion(data.vversion.v); chat->setVersion(data.vversion().v);
chat->invalidateParticipants(); chat->invalidateParticipants();
} }
chat->input = MTP_inputPeerChat(data.vid); chat->input = MTP_inputPeerChat(data.vid());
chat->setName(qs(data.vtitle)); chat->setName(qs(data.vtitle()));
chat->setPhoto(data.vphoto); chat->setPhoto(data.vphoto());
chat->date = data.vdate.v; chat->date = data.vdate().v;
chat->setAdminRights(data.has_admin_rights() if (const auto rights = data.vadmin_rights()) {
? data.vadmin_rights chat->setAdminRights(*rights);
: MTPChatAdminRights(MTP_chatAdminRights(MTP_flags(0)))); } else {
chat->setDefaultRestrictions(data.has_default_banned_rights() chat->setAdminRights(MTP_chatAdminRights(MTP_flags(0)));
? data.vdefault_banned_rights }
: MTPChatBannedRights( if (const auto rights = data.vdefault_banned_rights()) {
MTP_chatBannedRights(MTP_flags(0), MTP_int(0)))); chat->setDefaultRestrictions(*rights);
} else {
chat->setDefaultRestrictions(
MTP_chatBannedRights(MTP_flags(0), MTP_int(0)));
}
const auto &migratedTo = data.has_migrated_to() if (const auto migratedTo = data.vmigrated_to()) {
? data.vmigrated_to migratedTo->match([&](const MTPDinputChannel &input) {
: MTPInputChannel(MTP_inputChannelEmpty()); const auto channel = this->channel(input.vchannel_id().v);
migratedTo.match([&](const MTPDinputChannel & input) { channel->addFlags(MTPDchannel::Flag::f_megagroup);
const auto channel = this->channel(input.vchannel_id.v); if (!channel->access) {
channel->addFlags(MTPDchannel::Flag::f_megagroup); channel->input = MTP_inputPeerChannel(
if (!channel->access) { input.vchannel_id(),
channel->input = MTP_inputPeerChannel( input.vaccess_hash());
input.vchannel_id, channel->inputChannel = *migratedTo;
input.vaccess_hash); channel->access = input.vaccess_hash().v;
channel->inputChannel = migratedTo; }
channel->access = input.vaccess_hash.v; ApplyMigration(chat, channel);
} }, [](const MTPDinputChannelFromMessage &) {
ApplyMigration(chat, channel); LOG(("API Error: "
}, [](const MTPDinputChannelFromMessage &) { "migrated_to contains channel from message."));
LOG(("API Error: migrated_to contains channel from message.")); }, [](const MTPDinputChannelEmpty &) {
}, [](const MTPDinputChannelEmpty &) { });
}); }
chat->setFlags(data.vflags.v); chat->setFlags(data.vflags().v);
chat->count = data.vparticipants_count.v; chat->count = data.vparticipants_count().v;
if (canAddMembers != chat->canAddMembers()) { if (canAddMembers != chat->canAddMembers()) {
update.flags |= UpdateFlag::RightsChanged; update.flags |= UpdateFlag::RightsChanged;
@ -523,8 +542,8 @@ not_null<PeerData*> Session::processChat(const MTPChat &data) {
const auto canAddMembers = chat->canAddMembers(); const auto canAddMembers = chat->canAddMembers();
chat->input = MTP_inputPeerChat(data.vid); chat->input = MTP_inputPeerChat(data.vid());
chat->setName(qs(data.vtitle)); chat->setName(qs(data.vtitle()));
chat->setPhoto(MTP_chatPhotoEmpty()); chat->setPhoto(MTP_chatPhotoEmpty());
chat->date = 0; chat->date = 0;
chat->count = -1; chat->count = -1;
@ -546,10 +565,9 @@ not_null<PeerData*> Session::processChat(const MTPChat &data) {
LOG(("API Warning: not loaded minimal channel applied.")); LOG(("API Warning: not loaded minimal channel applied."));
} }
} else { } else {
const auto accessHash = data.has_access_hash() channel->input = MTP_inputPeerChannel(
? data.vaccess_hash data.vid(),
: MTP_long(0); MTP_long(data.vaccess_hash().value_or_empty()));
channel->input = MTP_inputPeerChannel(data.vid, accessHash);
} }
const auto wasInChannel = channel->amIn(); const auto wasInChannel = channel->amIn();
@ -557,52 +575,61 @@ not_null<PeerData*> Session::processChat(const MTPChat &data) {
const auto canViewMembers = channel->canViewMembers(); const auto canViewMembers = channel->canViewMembers();
const auto canAddMembers = channel->canAddMembers(); const auto canAddMembers = channel->canAddMembers();
if (data.has_participants_count()) { if (const auto count = data.vparticipants_count()) {
channel->setMembersCount(data.vparticipants_count.v); channel->setMembersCount(count->v);
}
if (const auto rights = data.vdefault_banned_rights()) {
channel->setDefaultRestrictions(*rights);
} else {
channel->setDefaultRestrictions(
MTP_chatBannedRights(MTP_flags(0), MTP_int(0)));
} }
channel->setDefaultRestrictions(data.has_default_banned_rights()
? data.vdefault_banned_rights
: MTPChatBannedRights(
MTP_chatBannedRights(MTP_flags(0), MTP_int(0))));
if (minimal) { if (minimal) {
auto mask = 0 auto mask = 0
| MTPDchannel::Flag::f_broadcast | MTPDchannel::Flag::f_broadcast
| MTPDchannel::Flag::f_verified | MTPDchannel::Flag::f_verified
| MTPDchannel::Flag::f_megagroup | MTPDchannel::Flag::f_megagroup
| MTPDchannel_ClientFlag::f_forbidden; | MTPDchannel_ClientFlag::f_forbidden;
channel->setFlags((channel->flags() & ~mask) | (data.vflags.v & mask)); channel->setFlags((channel->flags() & ~mask) | (data.vflags().v & mask));
} else { } else {
if (data.has_admin_rights()) { if (const auto rights = data.vadmin_rights()) {
channel->setAdminRights(data.vadmin_rights); channel->setAdminRights(*rights);
} else if (channel->hasAdminRights()) { } else if (channel->hasAdminRights()) {
channel->setAdminRights(MTP_chatAdminRights(MTP_flags(0))); channel->setAdminRights(MTP_chatAdminRights(MTP_flags(0)));
} }
if (data.has_banned_rights()) { if (const auto rights = data.vbanned_rights()) {
channel->setRestrictions(data.vbanned_rights); channel->setRestrictions(*rights);
} else if (channel->hasRestrictions()) { } else if (channel->hasRestrictions()) {
channel->setRestrictions(MTP_chatBannedRights(MTP_flags(0), MTP_int(0))); channel->setRestrictions(
MTP_chatBannedRights(MTP_flags(0), MTP_int(0)));
} }
channel->inputChannel = MTP_inputChannel(data.vid, data.vaccess_hash); const auto hash = data.vaccess_hash().value_or(channel->access);
channel->access = data.vaccess_hash.v; channel->inputChannel = MTP_inputChannel(
channel->date = data.vdate.v; data.vid(),
if (channel->version() < data.vversion.v) { MTP_long(hash));
channel->setVersion(data.vversion.v); channel->access = hash;
channel->date = data.vdate().v;
if (channel->version() < data.vversion().v) {
channel->setVersion(data.vversion().v);
} }
channel->setUnavailableReason(data.is_restricted() if (const auto restriction = data.vrestriction_reason()) {
? ExtractUnavailableReason(qs(data.vrestriction_reason)) channel->setUnavailableReason(qs(*restriction));
: QString()); } else {
channel->setFlags(data.vflags.v); channel->setUnavailableReason(QString());
//if (data.has_feed_id()) { // #feed }
// channel->setFeed(feed(data.vfeed_id.v)); channel->setFlags(data.vflags().v);
//if (const auto feedId = data.vfeed_id()) { // #feed
// channel->setFeed(feed(feedId->v));
//} else { //} else {
// channel->clearFeed(); // channel->clearFeed();
//} //}
} }
QString uname = data.has_username() ? TextUtilities::SingleLine(qs(data.vusername)) : QString(); channel->setName(
channel->setName(qs(data.vtitle), uname); qs(data.vtitle()),
TextUtilities::SingleLine(qs(data.vusername().value_or_empty())));
channel->setPhoto(data.vphoto); channel->setPhoto(data.vphoto());
if (wasInChannel != channel->amIn()) { if (wasInChannel != channel->amIn()) {
update.flags |= UpdateFlag::ChannelAmIn; update.flags |= UpdateFlag::ChannelAmIn;
@ -614,17 +641,17 @@ not_null<PeerData*> Session::processChat(const MTPChat &data) {
} }
}, [&](const MTPDchannelForbidden &data) { }, [&](const MTPDchannelForbidden &data) {
const auto channel = result->asChannel(); const auto channel = result->asChannel();
channel->input = MTP_inputPeerChannel(data.vid, data.vaccess_hash); channel->input = MTP_inputPeerChannel(data.vid(), data.vaccess_hash());
auto wasInChannel = channel->amIn(); auto wasInChannel = channel->amIn();
auto canViewAdmins = channel->canViewAdmins(); auto canViewAdmins = channel->canViewAdmins();
auto canViewMembers = channel->canViewMembers(); auto canViewMembers = channel->canViewMembers();
auto canAddMembers = channel->canAddMembers(); auto canAddMembers = channel->canAddMembers();
channel->inputChannel = MTP_inputChannel(data.vid, data.vaccess_hash); channel->inputChannel = MTP_inputChannel(data.vid(), data.vaccess_hash());
auto mask = mtpCastFlags(MTPDchannelForbidden::Flag::f_broadcast | MTPDchannelForbidden::Flag::f_megagroup); auto mask = mtpCastFlags(MTPDchannelForbidden::Flag::f_broadcast | MTPDchannelForbidden::Flag::f_megagroup);
channel->setFlags((channel->flags() & ~mask) | (mtpCastFlags(data.vflags) & mask) | MTPDchannel_ClientFlag::f_forbidden); channel->setFlags((channel->flags() & ~mask) | (mtpCastFlags(data.vflags()) & mask) | MTPDchannel_ClientFlag::f_forbidden);
if (channel->hasAdminRights()) { if (channel->hasAdminRights()) {
channel->setAdminRights(MTP_chatAdminRights(MTP_flags(0))); channel->setAdminRights(MTP_chatAdminRights(MTP_flags(0)));
@ -633,9 +660,9 @@ not_null<PeerData*> Session::processChat(const MTPChat &data) {
channel->setRestrictions(MTP_chatBannedRights(MTP_flags(0), MTP_int(0))); channel->setRestrictions(MTP_chatBannedRights(MTP_flags(0), MTP_int(0)));
} }
channel->setName(qs(data.vtitle), QString()); channel->setName(qs(data.vtitle()), QString());
channel->access = data.vaccess_hash.v; channel->access = data.vaccess_hash().v;
channel->setPhoto(MTP_chatPhotoEmpty()); channel->setPhoto(MTP_chatPhotoEmpty());
channel->date = 0; channel->date = 0;
channel->setMembersCount(0); channel->setMembersCount(0);
@ -684,15 +711,15 @@ PeerData *Session::processChats(const MTPVector<MTPChat> &data) {
void Session::applyMaximumChatVersions(const MTPVector<MTPChat> &data) { void Session::applyMaximumChatVersions(const MTPVector<MTPChat> &data) {
for (const auto &chat : data.v) { for (const auto &chat : data.v) {
chat.match([&](const MTPDchat &data) { chat.match([&](const MTPDchat &data) {
if (const auto chat = chatLoaded(data.vid.v)) { if (const auto chat = chatLoaded(data.vid().v)) {
if (data.vversion.v < chat->version()) { if (data.vversion().v < chat->version()) {
chat->setVersion(data.vversion.v); chat->setVersion(data.vversion().v);
} }
} }
}, [&](const MTPDchannel &data) { }, [&](const MTPDchannel &data) {
if (const auto channel = channelLoaded(data.vid.v)) { if (const auto channel = channelLoaded(data.vid().v)) {
if (data.vversion.v < channel->version()) { if (data.vversion().v < channel->version()) {
channel->setVersion(data.vversion.v); channel->setVersion(data.vversion().v);
} }
} }
}, [](const auto &) { }, [](const auto &) {
@ -1483,7 +1510,7 @@ void Session::applyPinnedChats(
const QVector<MTPDialogPeer> &list) { const QVector<MTPDialogPeer> &list) {
for (const auto &peer : list) { for (const auto &peer : list) {
peer.match([&](const MTPDdialogPeer &data) { peer.match([&](const MTPDdialogPeer &data) {
const auto history = this->history(peerFromMTP(data.vpeer)); const auto history = this->history(peerFromMTP(data.vpeer()));
if (folder) { if (folder) {
history->setFolder(folder); history->setFolder(folder);
} else { } else {
@ -1518,7 +1545,7 @@ void Session::applyDialogs(
void Session::applyDialog( void Session::applyDialog(
Data::Folder *requestFolder, Data::Folder *requestFolder,
const MTPDdialog &data) { const MTPDdialog &data) {
const auto peerId = peerFromMTP(data.vpeer); const auto peerId = peerFromMTP(data.vpeer());
if (!peerId) { if (!peerId) {
return; return;
} }
@ -1544,7 +1571,7 @@ void Session::applyDialog(
if (requestFolder) { if (requestFolder) {
LOG(("API Error: requestFolder != nullptr for dialogFolder.")); LOG(("API Error: requestFolder != nullptr for dialogFolder."));
} }
const auto folder = processFolder(data.vfolder); const auto folder = processFolder(data.vfolder());
folder->applyDialog(data); folder->applyDialog(data);
setPinnedFromDialog(folder, data.is_pinned()); setPinnedFromDialog(folder, data.is_pinned());
} }
@ -1580,27 +1607,23 @@ void Session::reorderTwoPinnedChats(
bool Session::checkEntitiesAndViewsUpdate(const MTPDmessage &data) { bool Session::checkEntitiesAndViewsUpdate(const MTPDmessage &data) {
const auto peer = [&] { const auto peer = [&] {
const auto result = peerFromMTP(data.vto_id); const auto result = peerFromMTP(data.vto_id());
return (data.has_from_id() && result == session().userPeerId()) if (const auto fromId = data.vfrom_id()) {
? peerFromUser(data.vfrom_id) if (result == session().userPeerId()) {
: result; return peerFromUser(*fromId);
}(); }
if (const auto existing = message(peerToChannel(peer), data.vid.v)) {
{
auto text = qs(data.vmessage);
auto entities = data.has_entities()
? TextUtilities::EntitiesFromMTP(data.ventities.v)
: EntitiesInText();
existing->setText({ std::move(text), std::move(entities) });
} }
existing->updateSentMedia(data.has_media() ? &data.vmedia : nullptr); return result;
existing->updateReplyMarkup(data.has_reply_markup() }();
? &data.vreply_markup if (const auto existing = message(peerToChannel(peer), data.vid().v)) {
: nullptr); existing->setText({
existing->updateForwardedInfo(data.has_fwd_from() qs(data.vmessage()),
? &data.vfwd_from TextUtilities::EntitiesFromMTP(data.ventities().value_or_empty())
: nullptr); });
existing->setViewsCount(data.has_views() ? data.vviews.v : -1); existing->updateSentMedia(data.vmedia());
existing->updateReplyMarkup(data.vreply_markup());
existing->updateForwardedInfo(data.vfwd_from());
existing->setViewsCount(data.vviews().value_or(-1));
existing->indexAsNewItem(); existing->indexAsNewItem();
requestItemTextRefresh(existing); requestItemTextRefresh(existing);
if (existing->mainView()) { if (existing->mainView()) {
@ -1618,12 +1641,15 @@ void Session::updateEditedMessage(const MTPMessage &data) {
return nullptr; return nullptr;
}, [&](const auto &data) { }, [&](const auto &data) {
const auto peer = [&] { const auto peer = [&] {
const auto result = peerFromMTP(data.vto_id); const auto result = peerFromMTP(data.vto_id());
return (data.has_from_id() && result == session().userPeerId()) if (const auto fromId = data.vfrom_id()) {
? peerFromUser(data.vfrom_id) if (result == session().userPeerId()) {
: result; return peerFromUser(*fromId);
}
}
return result;
}(); }();
return message(peerToChannel(peer), data.vid.v); return message(peerToChannel(peer), data.vid().v);
}); });
if (!existing) { if (!existing) {
return; return;
@ -2071,12 +2097,12 @@ not_null<PhotoData*> Session::processPhoto(const MTPPhoto &data) {
return data.match([&](const MTPDphoto &data) { return data.match([&](const MTPDphoto &data) {
return processPhoto(data); return processPhoto(data);
}, [&](const MTPDphotoEmpty &data) { }, [&](const MTPDphotoEmpty &data) {
return photo(data.vid.v); return photo(data.vid().v);
}); });
} }
not_null<PhotoData*> Session::processPhoto(const MTPDphoto &data) { not_null<PhotoData*> Session::processPhoto(const MTPDphoto &data) {
const auto result = photo(data.vid.v); const auto result = photo(data.vid().v);
photoApplyFields(result, data); photoApplyFields(result, data);
return result; return result;
} }
@ -2111,18 +2137,18 @@ not_null<PhotoData*> Session::processPhoto(
const auto large = image(LargeLevels); const auto large = image(LargeLevels);
return data.match([&](const MTPDphoto &data) { return data.match([&](const MTPDphoto &data) {
return photo( return photo(
data.vid.v, data.vid().v,
data.vaccess_hash.v, data.vaccess_hash().v,
data.vfile_reference.v, data.vfile_reference().v,
data.vdate.v, data.vdate().v,
data.vdc_id.v, data.vdc_id().v,
data.is_has_stickers(), data.is_has_stickers(),
thumbnailInline, thumbnailInline,
thumbnailSmall, thumbnailSmall,
thumbnail, thumbnail,
large); large);
}, [&](const MTPDphotoEmpty &data) { }, [&](const MTPDphotoEmpty &data) {
return photo(data.vid.v); return photo(data.vid().v);
}); });
} }
@ -2156,7 +2182,7 @@ void Session::photoConvert(
not_null<PhotoData*> original, not_null<PhotoData*> original,
const MTPPhoto &data) { const MTPPhoto &data) {
const auto id = data.match([](const auto &data) { const auto id = data.match([](const auto &data) {
return data.vid.v; return data.vid().v;
}); });
if (original->id != id) { if (original->id != id) {
auto i = _photos.find(id); auto i = _photos.find(id);
@ -2227,14 +2253,14 @@ void Session::photoApplyFields(
void Session::photoApplyFields( void Session::photoApplyFields(
not_null<PhotoData*> photo, not_null<PhotoData*> photo,
const MTPDphoto &data) { const MTPDphoto &data) {
const auto &sizes = data.vsizes.v; const auto &sizes = data.vsizes().v;
const auto find = [&](const QByteArray &levels) { const auto find = [&](const QByteArray &levels) {
const auto kInvalidIndex = int(levels.size()); const auto kInvalidIndex = int(levels.size());
const auto level = [&](const MTPPhotoSize &size) { const auto level = [&](const MTPPhotoSize &size) {
const auto letter = size.match([](const MTPDphotoSizeEmpty &) { const auto letter = size.match([](const MTPDphotoSizeEmpty &) {
return char(0); return char(0);
}, [](const auto &size) { }, [](const auto &size) {
return size.vtype.v.isEmpty() ? char(0) : size.vtype.v[0]; return size.vtype().v.isEmpty() ? char(0) : size.vtype().v[0];
}); });
const auto index = levels.indexOf(letter); const auto index = levels.indexOf(letter);
return (index >= 0) ? index : kInvalidIndex; return (index >= 0) ? index : kInvalidIndex;
@ -2256,10 +2282,10 @@ void Session::photoApplyFields(
if (thumbnailSmall && thumbnail && large) { if (thumbnailSmall && thumbnail && large) {
photoApplyFields( photoApplyFields(
photo, photo,
data.vaccess_hash.v, data.vaccess_hash().v,
data.vfile_reference.v, data.vfile_reference().v,
data.vdate.v, data.vdate().v,
data.vdc_id.v, data.vdc_id().v,
data.is_has_stickers(), data.is_has_stickers(),
thumbnailInline, thumbnailInline,
thumbnailSmall, thumbnailSmall,
@ -2308,13 +2334,13 @@ not_null<DocumentData*> Session::processDocument(const MTPDocument &data) {
return processDocument(data.c_document()); return processDocument(data.c_document());
case mtpc_documentEmpty: case mtpc_documentEmpty:
return document(data.c_documentEmpty().vid.v); return document(data.c_documentEmpty().vid().v);
} }
Unexpected("Type in Session::document()."); Unexpected("Type in Session::document().");
} }
not_null<DocumentData*> Session::processDocument(const MTPDdocument &data) { not_null<DocumentData*> Session::processDocument(const MTPDdocument &data) {
const auto result = document(data.vid.v); const auto result = document(data.vid().v);
documentApplyFields(result, data); documentApplyFields(result, data);
return result; return result;
} }
@ -2324,26 +2350,26 @@ not_null<DocumentData*> Session::processDocument(
QImage &&thumb) { QImage &&thumb) {
switch (data.type()) { switch (data.type()) {
case mtpc_documentEmpty: case mtpc_documentEmpty:
return document(data.c_documentEmpty().vid.v); return document(data.c_documentEmpty().vid().v);
case mtpc_document: { case mtpc_document: {
const auto &fields = data.c_document(); const auto &fields = data.c_document();
const auto mime = qs(fields.vmime_type); const auto mime = qs(fields.vmime_type());
const auto format = (mime == qstr("image/webp") const auto format = (mime == qstr("image/webp")
|| mime == qstr("application/x-tgsticker")) || mime == qstr("application/x-tgsticker"))
? "WEBP" ? "WEBP"
: "JPG"; : "JPG";
return document( return document(
fields.vid.v, fields.vid().v,
fields.vaccess_hash.v, fields.vaccess_hash().v,
fields.vfile_reference.v, fields.vfile_reference().v,
fields.vdate.v, fields.vdate().v,
fields.vattributes.v, fields.vattributes().v,
mime, mime,
ImagePtr(), ImagePtr(),
Images::Create(std::move(thumb), format), Images::Create(std::move(thumb), format),
fields.vdc_id.v, fields.vdc_id().v,
fields.vsize.v, fields.vsize().v,
StorageImageLocation()); StorageImageLocation());
} break; } break;
} }
@ -2383,8 +2409,8 @@ void Session::documentConvert(
const MTPDocument &data) { const MTPDocument &data) {
const auto id = [&] { const auto id = [&] {
switch (data.type()) { switch (data.type()) {
case mtpc_document: return data.c_document().vid.v; case mtpc_document: return data.c_document().vid().v;
case mtpc_documentEmpty: return data.c_documentEmpty().vid.v; case mtpc_documentEmpty: return data.c_documentEmpty().vid().v;
} }
Unexpected("Type in Session::documentConvert()."); Unexpected("Type in Session::documentConvert().");
}(); }();
@ -2441,16 +2467,16 @@ DocumentData *Session::documentFromWeb(
uint64(0), uint64(0),
QByteArray(), QByteArray(),
unixtime(), unixtime(),
data.vattributes.v, data.vattributes().v,
data.vmime_type.v, data.vmime_type().v,
ImagePtr(), ImagePtr(),
thumb, thumb,
MTP::maindc(), MTP::maindc(),
int32(0), // data.vsize.v int32(0), // data.vsize().v
StorageImageLocation()); StorageImageLocation());
result->setWebLocation(WebFileLocation( result->setWebLocation(WebFileLocation(
data.vurl.v, data.vurl().v,
data.vaccess_hash.v)); data.vaccess_hash().v));
return result; return result;
} }
@ -2462,14 +2488,14 @@ DocumentData *Session::documentFromWeb(
uint64(0), uint64(0),
QByteArray(), QByteArray(),
unixtime(), unixtime(),
data.vattributes.v, data.vattributes().v,
data.vmime_type.v, data.vmime_type().v,
ImagePtr(), ImagePtr(),
thumb, thumb,
MTP::maindc(), MTP::maindc(),
int32(0), // data.vsize.v int32(0), // data.vsize().v
StorageImageLocation()); StorageImageLocation());
result->setContentUrl(qs(data.vurl)); result->setContentUrl(qs(data.vurl()));
return result; return result;
} }
@ -2489,15 +2515,15 @@ void Session::documentApplyFields(
const auto thumbnail = Images::Create(data, thumbnailSize); const auto thumbnail = Images::Create(data, thumbnailSize);
documentApplyFields( documentApplyFields(
document, document,
data.vaccess_hash.v, data.vaccess_hash().v,
data.vfile_reference.v, data.vfile_reference().v,
data.vdate.v, data.vdate().v,
data.vattributes.v, data.vattributes().v,
qs(data.vmime_type), qs(data.vmime_type()),
Images::Create(data, thumbnailInline), Images::Create(data, thumbnailInline),
thumbnail, thumbnail,
data.vdc_id.v, data.vdc_id().v,
data.vsize.v, data.vsize().v,
thumbnail->location()); thumbnail->location());
} }
@ -2548,7 +2574,7 @@ not_null<WebPageData*> Session::processWebpage(const MTPWebPage &data) {
case mtpc_webPage: case mtpc_webPage:
return processWebpage(data.c_webPage()); return processWebpage(data.c_webPage());
case mtpc_webPageEmpty: { case mtpc_webPageEmpty: {
const auto result = webpage(data.c_webPageEmpty().vid.v); const auto result = webpage(data.c_webPageEmpty().vid().v);
if (result->pendingTill > 0) { if (result->pendingTill > 0) {
result->pendingTill = -1; // failed result->pendingTill = -1; // failed
} }
@ -2565,14 +2591,14 @@ not_null<WebPageData*> Session::processWebpage(const MTPWebPage &data) {
} }
not_null<WebPageData*> Session::processWebpage(const MTPDwebPage &data) { not_null<WebPageData*> Session::processWebpage(const MTPDwebPage &data) {
const auto result = webpage(data.vid.v); const auto result = webpage(data.vid().v);
webpageApplyFields(result, data); webpageApplyFields(result, data);
return result; return result;
} }
not_null<WebPageData*> Session::processWebpage(const MTPDwebPagePending &data) { not_null<WebPageData*> Session::processWebpage(const MTPDwebPagePending &data) {
constexpr auto kDefaultPendingTimeout = 60; constexpr auto kDefaultPendingTimeout = 60;
const auto result = webpage(data.vid.v); const auto result = webpage(data.vid().v);
webpageApplyFields( webpageApplyFields(
result, result,
WebPageType::Article, WebPageType::Article,
@ -2586,8 +2612,8 @@ not_null<WebPageData*> Session::processWebpage(const MTPDwebPagePending &data) {
WebPageCollage(), WebPageCollage(),
0, 0,
QString(), QString(),
data.vdate.v data.vdate().v
? data.vdate.v ? data.vdate().v
: (unixtime() + kDefaultPendingTimeout)); : (unixtime() + kDefaultPendingTimeout));
return result; return result;
} }
@ -2648,34 +2674,30 @@ void Session::webpageApplyFields(
not_null<WebPageData*> page, not_null<WebPageData*> page,
const MTPDwebPage &data) { const MTPDwebPage &data) {
auto description = TextWithEntities { auto description = TextWithEntities {
data.has_description() TextUtilities::Clean(qs(data.vdescription().value_or_empty()))
? TextUtilities::Clean(qs(data.vdescription))
: QString()
}; };
const auto siteName = data.has_site_name() const auto siteName = qs(data.vsite_name().value_or_empty());
? qs(data.vsite_name)
: QString();
auto parseFlags = TextParseLinks | TextParseMultiline | TextParseRichText; auto parseFlags = TextParseLinks | TextParseMultiline | TextParseRichText;
if (siteName == qstr("Twitter") || siteName == qstr("Instagram")) { if (siteName == qstr("Twitter") || siteName == qstr("Instagram")) {
parseFlags |= TextParseHashtags | TextParseMentions; parseFlags |= TextParseHashtags | TextParseMentions;
} }
TextUtilities::ParseEntities(description, parseFlags); TextUtilities::ParseEntities(description, parseFlags);
const auto pendingTill = TimeId(0); const auto pendingTill = TimeId(0);
const auto photo = data.vphoto();
const auto document = data.vdocument();
webpageApplyFields( webpageApplyFields(
page, page,
ParseWebPageType(data), ParseWebPageType(data),
qs(data.vurl), qs(data.vurl()),
qs(data.vdisplay_url), qs(data.vdisplay_url()),
siteName, siteName,
data.has_title() ? qs(data.vtitle) : QString(), qs(data.vtitle().value_or_empty()),
description, description,
data.has_photo() ? processPhoto(data.vphoto).get() : nullptr, photo ? processPhoto(*photo).get() : nullptr,
(data.has_document() document ? processDocument(*document).get() : nullptr,
? processDocument(data.vdocument).get()
: nullptr),
WebPageCollage(data), WebPageCollage(data),
data.has_duration() ? data.vduration.v : 0, data.vduration().value_or_empty(),
data.has_author() ? qs(data.vauthor) : QString(), qs(data.vauthor().value_or_empty()),
pendingTill); pendingTill);
} }
@ -2724,7 +2746,7 @@ not_null<GameData*> Session::game(GameId id) {
} }
not_null<GameData*> Session::processGame(const MTPDgame &data) { not_null<GameData*> Session::processGame(const MTPDgame &data) {
const auto result = game(data.vid.v); const auto result = game(data.vid().v);
gameApplyFields(result, data); gameApplyFields(result, data);
return result; return result;
} }
@ -2754,7 +2776,7 @@ void Session::gameConvert(
const MTPGame &data) { const MTPGame &data) {
Expects(data.type() == mtpc_game); Expects(data.type() == mtpc_game);
const auto id = data.c_game().vid.v; const auto id = data.c_game().vid().v;
if (original->id != id) { if (original->id != id) {
auto i = _games.find(id); auto i = _games.find(id);
if (i == _games.end()) { if (i == _games.end()) {
@ -2778,16 +2800,15 @@ void Session::gameConvert(
void Session::gameApplyFields( void Session::gameApplyFields(
not_null<GameData*> game, not_null<GameData*> game,
const MTPDgame &data) { const MTPDgame &data) {
const auto document = data.vdocument();
gameApplyFields( gameApplyFields(
game, game,
data.vaccess_hash.v, data.vaccess_hash().v,
qs(data.vshort_name), qs(data.vshort_name()),
qs(data.vtitle), qs(data.vtitle()),
qs(data.vdescription), qs(data.vdescription()),
processPhoto(data.vphoto), processPhoto(data.vphoto()),
(data.has_document() document ? processDocument(*document).get() : nullptr);
? processDocument(data.vdocument).get()
: nullptr));
} }
void Session::gameApplyFields( void Session::gameApplyFields(
@ -2820,7 +2841,7 @@ not_null<PollData*> Session::poll(PollId id) {
not_null<PollData*> Session::processPoll(const MTPPoll &data) { not_null<PollData*> Session::processPoll(const MTPPoll &data) {
return data.match([&](const MTPDpoll &data) { return data.match([&](const MTPDpoll &data) {
const auto id = data.vid.v; const auto id = data.vid().v;
const auto result = poll(id); const auto result = poll(id);
const auto changed = result->applyChanges(data); const auto changed = result->applyChanges(data);
if (changed) { if (changed) {
@ -2831,8 +2852,8 @@ not_null<PollData*> Session::processPoll(const MTPPoll &data) {
} }
not_null<PollData*> Session::processPoll(const MTPDmessageMediaPoll &data) { not_null<PollData*> Session::processPoll(const MTPDmessageMediaPoll &data) {
const auto result = processPoll(data.vpoll); const auto result = processPoll(data.vpoll());
const auto changed = result->applyResults(data.vresults); const auto changed = result->applyResults(data.vresults());
if (changed) { if (changed) {
notifyPollUpdateDelayed(result); notifyPollUpdateDelayed(result);
} }
@ -2841,21 +2862,22 @@ not_null<PollData*> Session::processPoll(const MTPDmessageMediaPoll &data) {
void Session::applyUpdate(const MTPDupdateMessagePoll &update) { void Session::applyUpdate(const MTPDupdateMessagePoll &update) {
const auto updated = [&] { const auto updated = [&] {
const auto i = _polls.find(update.vpoll_id.v); const auto poll = update.vpoll();
const auto i = _polls.find(update.vpoll_id().v);
return (i == end(_polls)) return (i == end(_polls))
? nullptr ? nullptr
: update.has_poll() : poll
? processPoll(update.vpoll).get() ? processPoll(*poll).get()
: i->second.get(); : i->second.get();
}(); }();
if (updated && updated->applyResults(update.vresults)) { if (updated && updated->applyResults(update.vresults())) {
notifyPollUpdateDelayed(updated); notifyPollUpdateDelayed(updated);
} }
} }
void Session::applyUpdate(const MTPDupdateChatParticipants &update) { void Session::applyUpdate(const MTPDupdateChatParticipants &update) {
const auto chatId = update.vparticipants.match([](const auto &update) { const auto chatId = update.vparticipants().match([](const auto &update) {
return update.vchat_id.v; return update.vchat_id().v;
}); });
if (const auto chat = chatLoaded(chatId)) { if (const auto chat = chatLoaded(chatId)) {
ApplyChatUpdate(chat, update); ApplyChatUpdate(chat, update);
@ -2868,25 +2890,25 @@ void Session::applyUpdate(const MTPDupdateChatParticipants &update) {
} }
void Session::applyUpdate(const MTPDupdateChatParticipantAdd &update) { void Session::applyUpdate(const MTPDupdateChatParticipantAdd &update) {
if (const auto chat = chatLoaded(update.vchat_id.v)) { if (const auto chat = chatLoaded(update.vchat_id().v)) {
ApplyChatUpdate(chat, update); ApplyChatUpdate(chat, update);
} }
} }
void Session::applyUpdate(const MTPDupdateChatParticipantDelete &update) { void Session::applyUpdate(const MTPDupdateChatParticipantDelete &update) {
if (const auto chat = chatLoaded(update.vchat_id.v)) { if (const auto chat = chatLoaded(update.vchat_id().v)) {
ApplyChatUpdate(chat, update); ApplyChatUpdate(chat, update);
} }
} }
void Session::applyUpdate(const MTPDupdateChatParticipantAdmin &update) { void Session::applyUpdate(const MTPDupdateChatParticipantAdmin &update) {
if (const auto chat = chatLoaded(update.vchat_id.v)) { if (const auto chat = chatLoaded(update.vchat_id().v)) {
ApplyChatUpdate(chat, update); ApplyChatUpdate(chat, update);
} }
} }
void Session::applyUpdate(const MTPDupdateChatDefaultBannedRights &update) { void Session::applyUpdate(const MTPDupdateChatDefaultBannedRights &update) {
if (const auto peer = peerLoaded(peerFromMTP(update.vpeer))) { if (const auto peer = peerLoaded(peerFromMTP(update.vpeer()))) {
if (const auto chat = peer->asChat()) { if (const auto chat = peer->asChat()) {
ApplyChatUpdate(chat, update); ApplyChatUpdate(chat, update);
} else if (const auto channel = peer->asChannel()) { } else if (const auto channel = peer->asChannel()) {
@ -3246,11 +3268,9 @@ not_null<Folder*> Session::processFolder(const MTPFolder &data) {
} }
not_null<Folder*> Session::processFolder(const MTPDfolder &data) { not_null<Folder*> Session::processFolder(const MTPDfolder &data) {
const auto result = folder(data.vid.v); const auto result = folder(data.vid().v);
//if (data.has_photo()) { //data.vphoto();
// data.vphoto; //data.vtitle();
//}
//data.vtitle;
return result; return result;
} }
// // #feed // // #feed
@ -3402,7 +3422,7 @@ void Session::applyNotifySetting(
} break; } break;
case mtpc_notifyPeer: { case mtpc_notifyPeer: {
const auto &data = notifyPeer.c_notifyPeer(); const auto &data = notifyPeer.c_notifyPeer();
if (const auto peer = peerLoaded(peerFromMTP(data.vpeer))) { if (const auto peer = peerLoaded(peerFromMTP(data.vpeer()))) {
if (peer->notifyChange(settings)) { if (peer->notifyChange(settings)) {
updateNotifySettingsLocal(peer); updateNotifySettingsLocal(peer);
} }
@ -3611,7 +3631,7 @@ PeerData *Session::proxyPromoted() const {
bool Session::updateWallpapers(const MTPaccount_WallPapers &data) { bool Session::updateWallpapers(const MTPaccount_WallPapers &data) {
return data.match([&](const MTPDaccount_wallPapers &data) { return data.match([&](const MTPDaccount_wallPapers &data) {
setWallpapers(data.vwallpapers.v, data.vhash.v); setWallpapers(data.vwallpapers().v, data.vhash().v);
return true; return true;
}, [&](const MTPDaccount_wallPapersNotModified &) { }, [&](const MTPDaccount_wallPapersNotModified &) {
return false; return false;

View file

@ -216,10 +216,12 @@ PeerId PeerFromMessage(const MTPmessage &message) {
return message.match([](const MTPDmessageEmpty &) { return message.match([](const MTPDmessageEmpty &) {
return PeerId(0); return PeerId(0);
}, [](const auto &message) { }, [](const auto &message) {
auto from_id = message.has_from_id() ? peerFromUser(message.vfrom_id) : 0; const auto fromId = message.vfrom_id();
auto to_id = peerFromMTP(message.vto_id); const auto toId = peerFromMTP(message.vto_id());
auto out = message.is_out(); const auto out = message.is_out();
return (out || !peerIsUser(to_id)) ? to_id : from_id; return (out || !fromId || !peerIsUser(toId))
? toId
: peerFromUser(*fromId);
}); });
} }
@ -227,15 +229,15 @@ MTPDmessage::Flags FlagsFromMessage(const MTPmessage &message) {
return message.match([](const MTPDmessageEmpty &) { return message.match([](const MTPDmessageEmpty &) {
return MTPDmessage::Flags(0); return MTPDmessage::Flags(0);
}, [](const MTPDmessage &message) { }, [](const MTPDmessage &message) {
return message.vflags.v; return message.vflags().v;
}, [](const MTPDmessageService &message) { }, [](const MTPDmessageService &message) {
return mtpCastFlags(message.vflags.v); return mtpCastFlags(message.vflags().v);
}); });
} }
MsgId IdFromMessage(const MTPmessage &message) { MsgId IdFromMessage(const MTPmessage &message) {
return message.match([](const auto &message) { return message.match([](const auto &message) {
return message.vid.v; return message.vid().v;
}); });
} }
@ -243,6 +245,6 @@ TimeId DateFromMessage(const MTPmessage &message) {
return message.match([](const MTPDmessageEmpty &) { return message.match([](const MTPDmessageEmpty &) {
return TimeId(0); return TimeId(0);
}, [](const auto &message) { }, [](const auto &message) {
return message.vdate.v; return message.vdate().v;
}); });
} }

View file

@ -183,9 +183,9 @@ inline MTPint peerToBareMTPInt(const PeerId &id) {
} }
inline PeerId peerFromMTP(const MTPPeer &peer) { inline PeerId peerFromMTP(const MTPPeer &peer) {
switch (peer.type()) { switch (peer.type()) {
case mtpc_peerUser: return peerFromUser(peer.c_peerUser().vuser_id); case mtpc_peerUser: return peerFromUser(peer.c_peerUser().vuser_id());
case mtpc_peerChat: return peerFromChat(peer.c_peerChat().vchat_id); case mtpc_peerChat: return peerFromChat(peer.c_peerChat().vchat_id());
case mtpc_peerChannel: return peerFromChannel(peer.c_peerChannel().vchannel_id); case mtpc_peerChannel: return peerFromChannel(peer.c_peerChannel().vchannel_id());
} }
return 0; return 0;
} }

View file

@ -74,7 +74,7 @@ void UserData::setIsContact(bool is) {
void UserData::setPhoto(const MTPUserProfilePhoto &photo) { void UserData::setPhoto(const MTPUserProfilePhoto &photo) {
if (photo.type() == mtpc_userProfilePhoto) { if (photo.type() == mtpc_userProfilePhoto) {
const auto &data = photo.c_userProfilePhoto(); const auto &data = photo.c_userProfilePhoto();
updateUserpic(data.vphoto_id.v, data.vdc_id.v, data.vphoto_small); updateUserpic(data.vphoto_id().v, data.vdc_id().v, data.vphoto_small());
} else { } else {
clearUserpic(); clearUserpic();
} }
@ -153,22 +153,22 @@ void UserData::setBotInfo(const MTPBotInfo &info) {
switch (info.type()) { switch (info.type()) {
case mtpc_botInfo: { case mtpc_botInfo: {
const auto &d(info.c_botInfo()); const auto &d(info.c_botInfo());
if (peerFromUser(d.vuser_id.v) != id || !botInfo) return; if (peerFromUser(d.vuser_id().v) != id || !botInfo) return;
QString desc = qs(d.vdescription); QString desc = qs(d.vdescription());
if (botInfo->description != desc) { if (botInfo->description != desc) {
botInfo->description = desc; botInfo->description = desc;
botInfo->text = Ui::Text::String(st::msgMinWidth); botInfo->text = Ui::Text::String(st::msgMinWidth);
} }
auto &v = d.vcommands.v; auto &v = d.vcommands().v;
botInfo->commands.reserve(v.size()); botInfo->commands.reserve(v.size());
auto changedCommands = false; auto changedCommands = false;
int32 j = 0; int32 j = 0;
for (const auto &command : v) { for (const auto &command : v) {
command.match([&](const MTPDbotCommand &data) { command.match([&](const MTPDbotCommand &data) {
const auto cmd = qs(data.vcommand); const auto cmd = qs(data.vcommand());
const auto desc = qs(data.vdescription); const auto desc = qs(data.vdescription());
if (botInfo->commands.size() <= j) { if (botInfo->commands.size() <= j) {
botInfo->commands.push_back(BotCommand(cmd, desc)); botInfo->commands.push_back(BotCommand(cmd, desc));
changedCommands = true; changedCommands = true;
@ -260,39 +260,39 @@ bool UserData::hasCalls() const {
namespace Data { namespace Data {
void ApplyUserUpdate(not_null<UserData*> user, const MTPDuserFull &update) { void ApplyUserUpdate(not_null<UserData*> user, const MTPDuserFull &update) {
user->owner().processUser(update.vuser); user->owner().processUser(update.vuser());
if (update.has_profile_photo()) { if (const auto photo = update.vprofile_photo()) {
user->owner().processPhoto(update.vprofile_photo); user->owner().processPhoto(*photo);
} }
const auto settings = update.vsettings.match([&]( const auto settings = update.vsettings().match([&](
const MTPDpeerSettings &data) { const MTPDpeerSettings &data) {
return data.vflags.v; return data.vflags().v;
}); });
user->setSettings(settings); user->setSettings(settings);
user->session().api().applyNotifySettings( user->session().api().applyNotifySettings(
MTP_inputNotifyPeer(user->input), MTP_inputNotifyPeer(user->input),
update.vnotify_settings); update.vnotify_settings());
if (update.has_bot_info()) { if (const auto info = update.vbot_info()) {
user->setBotInfo(update.vbot_info); user->setBotInfo(*info);
} else { } else {
user->setBotInfoVersion(-1); user->setBotInfoVersion(-1);
} }
if (update.has_pinned_msg_id()) { if (const auto pinned = update.vpinned_msg_id()) {
user->setPinnedMessageId(update.vpinned_msg_id.v); user->setPinnedMessageId(pinned->v);
} else { } else {
user->clearPinnedMessage(); user->clearPinnedMessage();
} }
user->setFullFlags(update.vflags.v); user->setFullFlags(update.vflags().v);
user->setIsBlocked(update.is_blocked()); user->setIsBlocked(update.is_blocked());
user->setCallsStatus(update.is_phone_calls_private() user->setCallsStatus(update.is_phone_calls_private()
? UserData::CallsStatus::Private ? UserData::CallsStatus::Private
: update.is_phone_calls_available() : update.is_phone_calls_available()
? UserData::CallsStatus::Enabled ? UserData::CallsStatus::Enabled
: UserData::CallsStatus::Disabled); : UserData::CallsStatus::Disabled);
user->setAbout(update.has_about() ? qs(update.vabout) : QString()); user->setAbout(qs(update.vabout().value_or_empty()));
user->setCommonChatsCount(update.vcommon_chats_count.v); user->setCommonChatsCount(update.vcommon_chats_count().v);
user->checkFolder(update.has_folder_id() ? update.vfolder_id.v : 0); user->checkFolder(update.vfolder_id().value_or_empty());
user->fullUpdated(); user->fullUpdated();
} }

View file

@ -316,29 +316,31 @@ std::optional<WallPaper> WallPaper::Create(const MTPDwallPaper &data) {
using Flag = MTPDwallPaper::Flag; using Flag = MTPDwallPaper::Flag;
const auto document = Auth().data().processDocument( const auto document = Auth().data().processDocument(
data.vdocument); data.vdocument());
if (!document->checkWallPaperProperties()) { if (!document->checkWallPaperProperties()) {
return std::nullopt; return std::nullopt;
} }
auto result = WallPaper(data.vid.v); auto result = WallPaper(data.vid().v);
result._accessHash = data.vaccess_hash.v; result._accessHash = data.vaccess_hash().v;
result._flags = data.vflags.v; result._flags = data.vflags().v;
result._slug = qs(data.vslug); result._slug = qs(data.vslug());
result._document = document; result._document = document;
if (data.has_settings()) { if (const auto settings = data.vsettings()) {
const auto isPattern = ((result._flags & Flag::f_pattern) != 0); const auto isPattern = ((result._flags & Flag::f_pattern) != 0);
data.vsettings.match([&](const MTPDwallPaperSettings &data) { settings->match([&](const MTPDwallPaperSettings &data) {
using Flag = MTPDwallPaperSettings::Flag; using Flag = MTPDwallPaperSettings::Flag;
result._settings = data.vflags.v; result._settings = data.vflags().v;
if (isPattern && data.has_background_color()) { const auto backgroundColor = data.vbackground_color();
if (isPattern && backgroundColor) {
result._backgroundColor = MaybeColorFromSerialized( result._backgroundColor = MaybeColorFromSerialized(
data.vbackground_color.v); backgroundColor->v);
} else { } else {
result._settings &= ~Flag::f_background_color; result._settings &= ~Flag::f_background_color;
} }
if (isPattern && data.has_intensity()) { const auto intensity = data.vintensity();
result._intensity = data.vintensity.v; if (isPattern && intensity) {
result._intensity = intensity->v;
} else { } else {
result._settings &= ~Flag::f_intensity; result._settings &= ~Flag::f_intensity;
} }

View file

@ -62,18 +62,18 @@ WebPageCollage ExtractCollage(
result.items.reserve(count); result.items.reserve(count);
for (const auto &item : items) { for (const auto &item : items) {
const auto good = item.match([&](const MTPDpageBlockPhoto &data) { const auto good = item.match([&](const MTPDpageBlockPhoto &data) {
const auto photo = storage.photo(data.vphoto_id.v); const auto photo = storage.photo(data.vphoto_id().v);
if (photo->isNull()) { if (photo->isNull()) {
return false; return false;
} }
result.items.push_back(photo); result.items.emplace_back(photo);
return true; return true;
}, [&](const MTPDpageBlockVideo &data) { }, [&](const MTPDpageBlockVideo &data) {
const auto document = storage.document(data.vvideo_id.v); const auto document = storage.document(data.vvideo_id().v);
if (!document->isVideoFile()) { if (!document->isVideoFile()) {
return false; return false;
} }
result.items.push_back(document); result.items.emplace_back(document);
return true; return true;
}, [](const auto &) -> bool { }, [](const auto &) -> bool {
Unexpected("Type of block in Collage."); Unexpected("Type of block in Collage.");
@ -86,19 +86,20 @@ WebPageCollage ExtractCollage(
} }
WebPageCollage ExtractCollage(const MTPDwebPage &data) { WebPageCollage ExtractCollage(const MTPDwebPage &data) {
if (!data.has_cached_page()) { const auto page = data.vcached_page();
if (!page) {
return {}; return {};
} }
const auto processMedia = [&] { const auto processMedia = [&] {
if (data.has_photo()) { if (const auto photo = data.vphoto()) {
Auth().data().processPhoto(data.vphoto); Auth().data().processPhoto(*photo);
} }
if (data.has_document()) { if (const auto document = data.vdocument()) {
Auth().data().processDocument(data.vdocument); Auth().data().processDocument(*document);
} }
}; };
return data.vcached_page.match([&](const auto &page) { return page->match([&](const auto &page) {
for (const auto &block : page.vblocks.v) { for (const auto &block : page.vblocks().v) {
switch (block.type()) { switch (block.type()) {
case mtpc_pageBlockPhoto: case mtpc_pageBlockPhoto:
case mtpc_pageBlockVideo: case mtpc_pageBlockVideo:
@ -110,15 +111,15 @@ WebPageCollage ExtractCollage(const MTPDwebPage &data) {
case mtpc_pageBlockSlideshow: case mtpc_pageBlockSlideshow:
processMedia(); processMedia();
return ExtractCollage( return ExtractCollage(
block.c_pageBlockSlideshow().vitems.v, block.c_pageBlockSlideshow().vitems().v,
page.vphotos.v, page.vphotos().v,
page.vdocuments.v); page.vdocuments().v);
case mtpc_pageBlockCollage: case mtpc_pageBlockCollage:
processMedia(); processMedia();
return ExtractCollage( return ExtractCollage(
block.c_pageBlockCollage().vitems.v, block.c_pageBlockCollage().vitems().v,
page.vphotos.v, page.vphotos().v,
page.vdocuments.v); page.vdocuments().v);
default: break; default: break;
} }
} }
@ -129,8 +130,8 @@ WebPageCollage ExtractCollage(const MTPDwebPage &data) {
} // namespace } // namespace
WebPageType ParseWebPageType(const MTPDwebPage &page) { WebPageType ParseWebPageType(const MTPDwebPage &page) {
const auto type = page.has_type() ? qs(page.vtype) : QString(); const auto type = qs(page.vtype().value_or_empty());
if (type == qstr("video") || page.has_embed_url()) { if (type == qstr("video") || page.vembed_url()) {
return WebPageType::Video; return WebPageType::Video;
} else if (type == qstr("photo")) { } else if (type == qstr("photo")) {
return WebPageType::Photo; return WebPageType::Photo;
@ -138,7 +139,7 @@ WebPageType ParseWebPageType(const MTPDwebPage &page) {
return WebPageType::Profile; return WebPageType::Profile;
} else if (type == qstr("telegram_background")) { } else if (type == qstr("telegram_background")) {
return WebPageType::WallPaper; return WebPageType::WallPaper;
} else if (page.has_cached_page()) { } else if (page.vcached_page()) {
return WebPageType::ArticleWithIV; return WebPageType::ArticleWithIV;
} else { } else {
return WebPageType::Article; return WebPageType::Article;

View file

@ -85,11 +85,11 @@ void PinnedList::applyList(
clear(); clear();
for (const auto &peer : ranges::view::reverse(list)) { for (const auto &peer : ranges::view::reverse(list)) {
peer.match([&](const MTPDdialogPeer &data) { peer.match([&](const MTPDdialogPeer &data) {
if (const auto peerId = peerFromMTP(data.vpeer)) { if (const auto peerId = peerFromMTP(data.vpeer())) {
setPinned(owner->history(peerId), true); setPinned(owner->history(peerId), true);
} }
}, [&](const MTPDdialogPeerFolder &data) { }, [&](const MTPDdialogPeerFolder &data) {
const auto folderId = data.vfolder_id.v; const auto folderId = data.vfolder_id().v;
setPinned(owner->folder(folderId), true); setPinned(owner->folder(folderId), true);
}); });
} }

View file

@ -999,10 +999,10 @@ void Widget::searchReceived(
auto &d = result.c_messages_messages(); auto &d = result.c_messages_messages();
if (_searchRequest != 0) { if (_searchRequest != 0) {
// Don't apply cached data! // Don't apply cached data!
session().data().processUsers(d.vusers); session().data().processUsers(d.vusers());
session().data().processChats(d.vchats); session().data().processChats(d.vchats());
} }
auto &msgs = d.vmessages.v; auto &msgs = d.vmessages().v;
_inner->searchReceived(msgs, type, msgs.size()); _inner->searchReceived(msgs, type, msgs.size());
if (type == SearchRequestType::MigratedFromStart || type == SearchRequestType::MigratedFromOffset) { if (type == SearchRequestType::MigratedFromStart || type == SearchRequestType::MigratedFromOffset) {
_searchFullMigrated = true; _searchFullMigrated = true;
@ -1015,17 +1015,18 @@ void Widget::searchReceived(
auto &d = result.c_messages_messagesSlice(); auto &d = result.c_messages_messagesSlice();
if (_searchRequest != 0) { if (_searchRequest != 0) {
// Don't apply cached data! // Don't apply cached data!
session().data().processUsers(d.vusers); session().data().processUsers(d.vusers());
session().data().processChats(d.vchats); session().data().processChats(d.vchats());
} }
auto &msgs = d.vmessages.v; auto &msgs = d.vmessages().v;
const auto someAdded = _inner->searchReceived(msgs, type, d.vcount.v); const auto someAdded = _inner->searchReceived(msgs, type, d.vcount().v);
const auto rateUpdated = d.has_next_rate() && (d.vnext_rate.v != _searchNextRate); const auto nextRate = d.vnext_rate();
const auto rateUpdated = nextRate && (nextRate->v != _searchNextRate);
const auto finished = (type == SearchRequestType::FromStart || type == SearchRequestType::FromOffset) const auto finished = (type == SearchRequestType::FromStart || type == SearchRequestType::FromOffset)
? !rateUpdated ? !rateUpdated
: !someAdded; : !someAdded;
if (rateUpdated) { if (rateUpdated) {
_searchNextRate = d.vnext_rate.v; _searchNextRate = nextRate->v;
} }
if (finished) { if (finished) {
if (type == SearchRequestType::MigratedFromStart || type == SearchRequestType::MigratedFromOffset) { if (type == SearchRequestType::MigratedFromStart || type == SearchRequestType::MigratedFromOffset) {
@ -1040,7 +1041,7 @@ void Widget::searchReceived(
auto &d = result.c_messages_channelMessages(); auto &d = result.c_messages_channelMessages();
if (const auto peer = _searchInChat.peer()) { if (const auto peer = _searchInChat.peer()) {
if (const auto channel = peer->asChannel()) { if (const auto channel = peer->asChannel()) {
channel->ptsReceived(d.vpts.v); channel->ptsReceived(d.vpts().v);
} else { } else {
LOG(("API Error: " LOG(("API Error: "
"received messages.channelMessages when no channel " "received messages.channelMessages when no channel "
@ -1053,11 +1054,11 @@ void Widget::searchReceived(
} }
if (_searchRequest != 0) { if (_searchRequest != 0) {
// Don't apply cached data! // Don't apply cached data!
session().data().processUsers(d.vusers); session().data().processUsers(d.vusers());
session().data().processChats(d.vchats); session().data().processChats(d.vchats());
} }
auto &msgs = d.vmessages.v; auto &msgs = d.vmessages().v;
if (!_inner->searchReceived(msgs, type, d.vcount.v)) { if (!_inner->searchReceived(msgs, type, d.vcount().v)) {
if (type == SearchRequestType::MigratedFromStart || type == SearchRequestType::MigratedFromOffset) { if (type == SearchRequestType::MigratedFromStart || type == SearchRequestType::MigratedFromOffset) {
_searchFullMigrated = true; _searchFullMigrated = true;
} else { } else {
@ -1099,9 +1100,9 @@ void Widget::peerSearchReceived(
switch (result.type()) { switch (result.type()) {
case mtpc_contacts_found: { case mtpc_contacts_found: {
auto &d = result.c_contacts_found(); auto &d = result.c_contacts_found();
session().data().processUsers(d.vusers); session().data().processUsers(d.vusers());
session().data().processChats(d.vchats); session().data().processChats(d.vchats());
_inner->peerSearchReceived(q, d.vmy_results.v, d.vresults.v); _inner->peerSearchReceived(q, d.vmy_results().v, d.vresults().v);
} break; } break;
} }

File diff suppressed because it is too large Load diff

View file

@ -50,40 +50,40 @@ LocationKey ComputeLocationKey(const Data::FileLocation &value) {
result.type = value.dcId; result.type = value.dcId;
value.data.match([&](const MTPDinputFileLocation &data) { value.data.match([&](const MTPDinputFileLocation &data) {
result.type |= (1ULL << 24); result.type |= (1ULL << 24);
result.type |= (uint64(uint32(data.vlocal_id.v)) << 32); result.type |= (uint64(uint32(data.vlocal_id().v)) << 32);
result.id = data.vvolume_id.v; result.id = data.vvolume_id().v;
}, [&](const MTPDinputDocumentFileLocation &data) { }, [&](const MTPDinputDocumentFileLocation &data) {
const auto letter = data.vthumb_size.v.isEmpty() const auto letter = data.vthumb_size().v.isEmpty()
? char(0) ? char(0)
: data.vthumb_size.v[0]; : data.vthumb_size().v[0];
result.type |= (2ULL << 24); result.type |= (2ULL << 24);
result.type |= (uint64(uint32(letter)) << 16); result.type |= (uint64(uint32(letter)) << 16);
result.id = data.vid.v; result.id = data.vid().v;
}, [&](const MTPDinputSecureFileLocation &data) { }, [&](const MTPDinputSecureFileLocation &data) {
result.type |= (3ULL << 24); result.type |= (3ULL << 24);
result.id = data.vid.v; result.id = data.vid().v;
}, [&](const MTPDinputEncryptedFileLocation &data) { }, [&](const MTPDinputEncryptedFileLocation &data) {
result.type |= (4ULL << 24); result.type |= (4ULL << 24);
result.id = data.vid.v; result.id = data.vid().v;
}, [&](const MTPDinputTakeoutFileLocation &data) { }, [&](const MTPDinputTakeoutFileLocation &data) {
result.type |= (5ULL << 24); result.type |= (5ULL << 24);
}, [&](const MTPDinputPhotoFileLocation &data) { }, [&](const MTPDinputPhotoFileLocation &data) {
const auto letter = data.vthumb_size.v.isEmpty() const auto letter = data.vthumb_size().v.isEmpty()
? char(0) ? char(0)
: data.vthumb_size.v[0]; : data.vthumb_size().v[0];
result.type |= (6ULL << 24); result.type |= (6ULL << 24);
result.type |= (uint64(uint32(letter)) << 16); result.type |= (uint64(uint32(letter)) << 16);
result.id = data.vid.v; result.id = data.vid().v;
}, [&](const MTPDinputPeerPhotoFileLocation &data) { }, [&](const MTPDinputPeerPhotoFileLocation &data) {
const auto letter = data.is_big() ? char(1) : char(0); const auto letter = data.is_big() ? char(1) : char(0);
result.type |= (7ULL << 24); result.type |= (7ULL << 24);
result.type |= (uint64(uint32(data.vlocal_id.v)) << 32); result.type |= (uint64(uint32(data.vlocal_id().v)) << 32);
result.type |= (uint64(uint32(letter)) << 16); result.type |= (uint64(uint32(letter)) << 16);
result.id = data.vvolume_id.v; result.id = data.vvolume_id().v;
}, [&](const MTPDinputStickerSetThumb &data) { }, [&](const MTPDinputStickerSetThumb &data) {
result.type |= (8ULL << 24); result.type |= (8ULL << 24);
result.type |= (uint64(uint32(data.vlocal_id.v)) << 32); result.type |= (uint64(uint32(data.vlocal_id().v)) << 32);
result.id = data.vvolume_id.v; result.id = data.vvolume_id().v;
}); });
return result; return result;
} }
@ -386,9 +386,12 @@ auto ApiWrap::fileRequest(const Data::FileLocation &location, int offset) {
)).fail([=](RPCError &&result) { )).fail([=](RPCError &&result) {
if (result.type() == qstr("TAKEOUT_FILE_EMPTY") if (result.type() == qstr("TAKEOUT_FILE_EMPTY")
&& _otherDataProcess != nullptr) { && _otherDataProcess != nullptr) {
filePartDone(0, MTP_upload_file(MTP_storage_filePartial(), filePartDone(
MTP_int(0), 0,
MTP_bytes(QByteArray()))); MTP_upload_file(
MTP_storage_filePartial(),
MTP_int(0),
MTP_bytes()));
} else if (result.type() == qstr("LOCATION_INVALID") } else if (result.type() == qstr("LOCATION_INVALID")
|| result.type() == qstr("VERSION_INVALID")) { || result.type() == qstr("VERSION_INVALID")) {
filePartUnavailable(); filePartUnavailable();
@ -481,9 +484,9 @@ void ApiWrap::requestUserpicsCount() {
_startProcess->info.userpicsCount = result.match( _startProcess->info.userpicsCount = result.match(
[](const MTPDphotos_photos &data) { [](const MTPDphotos_photos &data) {
return int(data.vphotos.v.size()); return int(data.vphotos().v.size());
}, [](const MTPDphotos_photosSlice &data) { }, [](const MTPDphotos_photosSlice &data) {
return data.vcount.v; return data.vcount().v;
}); });
sendNextStartRequest(); sendNextStartRequest();
@ -540,9 +543,9 @@ void ApiWrap::requestDialogsCount() {
const auto count = result.match( const auto count = result.match(
[](const MTPDmessages_dialogs &data) { [](const MTPDmessages_dialogs &data) {
return int(data.vdialogs.v.size()); return int(data.vdialogs().v.size());
}, [](const MTPDmessages_dialogsSlice &data) { }, [](const MTPDmessages_dialogsSlice &data) {
return data.vcount.v; return data.vcount().v;
}, [](const MTPDmessages_dialogsNotModified &data) { }, [](const MTPDmessages_dialogsNotModified &data) {
return -1; return -1;
}); });
@ -654,7 +657,7 @@ void ApiWrap::startMainSession(FnMut<void()> done) {
)).done([=, done = std::move(done)]( )).done([=, done = std::move(done)](
const MTPaccount_Takeout &result) mutable { const MTPaccount_Takeout &result) mutable {
_takeoutId = result.match([](const MTPDaccount_takeout &data) { _takeoutId = result.match([](const MTPDaccount_takeout &data) {
return data.vid.v; return data.vid().v;
}); });
done(); done();
}).fail([=](RPCError &&result) { }).fail([=](RPCError &&result) {
@ -669,7 +672,7 @@ void ApiWrap::requestPersonalInfo(FnMut<void(Data::PersonalInfo&&)> done) {
Expects(result.type() == mtpc_userFull); Expects(result.type() == mtpc_userFull);
const auto &full = result.c_userFull(); const auto &full = result.c_userFull();
if (full.vuser.type() == mtpc_user) { if (full.vuser().type() == mtpc_user) {
done(Data::ParsePersonalInfo(result)); done(Data::ParsePersonalInfo(result));
} else { } else {
error("Bad user type."); error("Bad user type.");
@ -726,9 +729,9 @@ void ApiWrap::requestUserpics(
auto startInfo = result.match( auto startInfo = result.match(
[](const MTPDphotos_photos &data) { [](const MTPDphotos_photos &data) {
return Data::UserpicsInfo{ data.vphotos.v.size() }; return Data::UserpicsInfo{ data.vphotos().v.size() };
}, [](const MTPDphotos_photosSlice &data) { }, [](const MTPDphotos_photosSlice &data) {
return Data::UserpicsInfo{ data.vcount.v }; return Data::UserpicsInfo{ data.vcount().v };
}); });
if (!_userpicsProcess->start(std::move(startInfo))) { if (!_userpicsProcess->start(std::move(startInfo))) {
return; return;
@ -746,7 +749,7 @@ void ApiWrap::handleUserpicsSlice(const MTPphotos_Photos &result) {
_userpicsProcess->lastSlice = true; _userpicsProcess->lastSlice = true;
} }
loadUserpicsFiles(Data::ParseUserpicsSlice( loadUserpicsFiles(Data::ParseUserpicsSlice(
data.vphotos, data.vphotos(),
_userpicsProcess->processed)); _userpicsProcess->processed));
}); });
} }
@ -883,10 +886,10 @@ void ApiWrap::requestTopPeersSlice() {
}, [](const MTPDcontacts_topPeersDisabled &data) { }, [](const MTPDcontacts_topPeersDisabled &data) {
return true; return true;
}, [&](const MTPDcontacts_topPeers &data) { }, [&](const MTPDcontacts_topPeers &data) {
for (const auto &category : data.vcategories.v) { for (const auto &category : data.vcategories().v) {
const auto loaded = category.match( const auto loaded = category.match(
[&](const MTPDtopPeerCategoryPeers &data) { [&](const MTPDtopPeerCategoryPeers &data) {
return offset + data.vpeers.v.size() >= data.vcount.v; return offset + data.vpeers().v.size() >= data.vcount().v;
}); });
if (!loaded) { if (!loaded) {
return false; return false;
@ -954,11 +957,11 @@ void ApiWrap::requestMessagesCount(int localSplitIndex) {
const auto count = result.match( const auto count = result.match(
[](const MTPDmessages_messages &data) { [](const MTPDmessages_messages &data) {
return data.vmessages.v.size(); return data.vmessages().v.size();
}, [](const MTPDmessages_messagesSlice &data) { }, [](const MTPDmessages_messagesSlice &data) {
return data.vcount.v; return data.vcount().v;
}, [](const MTPDmessages_channelMessages &data) { }, [](const MTPDmessages_channelMessages &data) {
return data.vcount.v; return data.vcount().v;
}, [](const MTPDmessages_messagesNotModified &data) { }, [](const MTPDmessages_messagesNotModified &data) {
return -1; return -1;
}); });
@ -1068,16 +1071,16 @@ void ApiWrap::requestSinglePeerDialog() {
)).done(std::move(doneSinglePeer)).send(); )).done(std::move(doneSinglePeer)).send();
}; };
_settings->singlePeer.match([&](const MTPDinputPeerUser &data) { _settings->singlePeer.match([&](const MTPDinputPeerUser &data) {
requestUser(MTP_inputUser(data.vuser_id, data.vaccess_hash)); requestUser(MTP_inputUser(data.vuser_id(), data.vaccess_hash()));
}, [&](const MTPDinputPeerChat &data) { }, [&](const MTPDinputPeerChat &data) {
mainRequest(MTPmessages_GetChats( mainRequest(MTPmessages_GetChats(
MTP_vector<MTPint>(1, data.vchat_id) MTP_vector<MTPint>(1, data.vchat_id())
)).done(std::move(doneSinglePeer)).send(); )).done(std::move(doneSinglePeer)).send();
}, [&](const MTPDinputPeerChannel &data) { }, [&](const MTPDinputPeerChannel &data) {
mainRequest(MTPchannels_GetChannels( mainRequest(MTPchannels_GetChannels(
MTP_vector<MTPInputChannel>( MTP_vector<MTPInputChannel>(
1, 1,
MTP_inputChannel(data.vchannel_id, data.vaccess_hash)) MTP_inputChannel(data.vchannel_id(), data.vaccess_hash()))
)).done(std::move(doneSinglePeer)).send(); )).done(std::move(doneSinglePeer)).send();
}, [&](const MTPDinputPeerSelf &data) { }, [&](const MTPDinputPeerSelf &data) {
requestUser(MTP_inputUserSelf()); requestUser(MTP_inputUserSelf());
@ -1117,7 +1120,7 @@ void ApiWrap::requestDialogsSlice() {
[](const MTPDmessages_dialogs &data) { [](const MTPDmessages_dialogs &data) {
return true; return true;
}, [](const MTPDmessages_dialogsSlice &data) { }, [](const MTPDmessages_dialogsSlice &data) {
return data.vdialogs.v.isEmpty(); return data.vdialogs().v.isEmpty();
}, [](const MTPDmessages_dialogsNotModified &data) { }, [](const MTPDmessages_dialogsNotModified &data) {
return true; return true;
}); });
@ -1201,21 +1204,21 @@ void ApiWrap::requestLeftChannelsSliceGeneric(FnMut<void()> done) {
const auto process = _leftChannelsProcess.get(); const auto process = _leftChannelsProcess.get();
process->offset += result.match( process->offset += result.match(
[](const auto &data) { [](const auto &data) {
return int(data.vchats.v.size()); return int(data.vchats().v.size());
}); });
process->fullCount = result.match( process->fullCount = result.match(
[](const MTPDmessages_chats &data) { [](const MTPDmessages_chats &data) {
return int(data.vchats.v.size()); return int(data.vchats().v.size());
}, [](const MTPDmessages_chatsSlice &data) { }, [](const MTPDmessages_chatsSlice &data) {
return data.vcount.v; return data.vcount().v;
}); });
process->finished = result.match( process->finished = result.match(
[](const MTPDmessages_chats &data) { [](const MTPDmessages_chats &data) {
return true; return true;
}, [](const MTPDmessages_chatsSlice &data) { }, [](const MTPDmessages_chatsSlice &data) {
return data.vchats.v.isEmpty(); return data.vchats().v.isEmpty();
}); });
if (process->progress) { if (process->progress) {
@ -1289,9 +1292,9 @@ void ApiWrap::requestMessagesSlice() {
} }
loadMessagesFiles(Data::ParseMessagesSlice( loadMessagesFiles(Data::ParseMessagesSlice(
_chatProcess->context, _chatProcess->context,
data.vmessages, data.vmessages(),
data.vusers, data.vusers(),
data.vchats, data.vchats(),
_chatProcess->info.relativePath)); _chatProcess->info.relativePath));
}); });
}); });
@ -1315,7 +1318,7 @@ void ApiWrap::requestChatMessages(
splitRequest(splitIndex, MTPmessages_Search( splitRequest(splitIndex, MTPmessages_Search(
MTP_flags(MTPmessages_Search::Flag::f_from_id), MTP_flags(MTPmessages_Search::Flag::f_from_id),
_chatProcess->info.input, _chatProcess->info.input,
MTP_string(""), // query MTP_string(), // query
_user, _user,
MTP_inputMessagesFilterEmpty(), MTP_inputMessagesFilterEmpty(),
MTP_int(0), // min_date MTP_int(0), // min_date
@ -1646,7 +1649,7 @@ void ApiWrap::filePartDone(int offset, const MTPupload_File &result) {
return; return;
} }
const auto &data = result.c_upload_file(); const auto &data = result.c_upload_file();
if (data.vbytes.v.isEmpty()) { if (data.vbytes().v.isEmpty()) {
if (_fileProcess->size > 0) { if (_fileProcess->size > 0) {
error("Empty bytes received in file part."); error("Empty bytes received in file part.");
return; return;
@ -1665,7 +1668,7 @@ void ApiWrap::filePartDone(int offset, const MTPupload_File &result) {
[](const Request &request) { return request.offset; }); [](const Request &request) { return request.offset; });
Assert(i != end(requests)); Assert(i != end(requests));
i->bytes = data.vbytes.v; i->bytes = data.vbytes().v;
auto &file = _fileProcess->file; auto &file = _fileProcess->file;
while (!requests.empty() && !requests.front().bytes.isEmpty()) { while (!requests.empty() && !requests.front().bytes.isEmpty()) {

View file

@ -36,15 +36,15 @@ constexpr auto kMegabyte = 1024 * 1024;
PeerId ReadPeerId(const MTPInputPeer &data) { PeerId ReadPeerId(const MTPInputPeer &data) {
return data.match([](const MTPDinputPeerUser &data) { return data.match([](const MTPDinputPeerUser &data) {
return peerFromUser(data.vuser_id.v); return peerFromUser(data.vuser_id().v);
}, [](const MTPDinputPeerUserFromMessage &data) { }, [](const MTPDinputPeerUserFromMessage &data) {
return peerFromUser(data.vuser_id.v); return peerFromUser(data.vuser_id().v);
}, [](const MTPDinputPeerChat &data) { }, [](const MTPDinputPeerChat &data) {
return peerFromChat(data.vchat_id.v); return peerFromChat(data.vchat_id().v);
}, [](const MTPDinputPeerChannel &data) { }, [](const MTPDinputPeerChannel &data) {
return peerFromChannel(data.vchannel_id.v); return peerFromChannel(data.vchannel_id().v);
}, [](const MTPDinputPeerChannelFromMessage &data) { }, [](const MTPDinputPeerChannelFromMessage &data) {
return peerFromChannel(data.vchannel_id.v); return peerFromChannel(data.vchannel_id().v);
}, [](const MTPDinputPeerSelf &data) { }, [](const MTPDinputPeerSelf &data) {
return Auth().userPeerId(); return Auth().userPeerId();
}, [](const MTPDinputPeerEmpty &data) { }, [](const MTPDinputPeerEmpty &data) {

View file

@ -396,7 +396,7 @@ void InnerWidget::requestAdmins() {
list list
) | ranges::view::transform([&](const MTPChannelParticipant &p) { ) | ranges::view::transform([&](const MTPChannelParticipant &p) {
const auto userId = p.match([](const auto &data) { const auto userId = p.match([](const auto &data) {
return data.vuser_id.v; return data.vuser_id().v;
}); });
const auto canEdit = p.match([]( const auto canEdit = p.match([](
const MTPDchannelParticipantAdmin &data) { const MTPDchannelParticipantAdmin &data) {
@ -622,10 +622,10 @@ void InnerWidget::preloadMore(Direction direction) {
requestId = 0; requestId = 0;
auto &results = result.c_channels_adminLogResults(); auto &results = result.c_channels_adminLogResults();
_channel->owner().processUsers(results.vusers); _channel->owner().processUsers(results.vusers());
_channel->owner().processChats(results.vchats); _channel->owner().processChats(results.vchats());
if (!loadedFlag) { if (!loadedFlag) {
addEvents(direction, results.vevents.v); addEvents(direction, results.vevents().v);
} }
}).fail([this, &requestId, &loadedFlag](const RPCError &error) { }).fail([this, &requestId, &loadedFlag](const RPCError &error) {
requestId = 0; requestId = 0;
@ -656,7 +656,7 @@ void InnerWidget::addEvents(Direction direction, const QVector<MTPChannelAdminLo
addToItems.reserve(oldItemsCount + events.size() * 2); addToItems.reserve(oldItemsCount + events.size() * 2);
for (const auto &event : events) { for (const auto &event : events) {
event.match([&](const MTPDchannelAdminLogEvent &data) { event.match([&](const MTPDchannelAdminLogEvent &data) {
const auto id = data.vid.v; const auto id = data.vid().v;
if (_eventIds.find(id) != _eventIds.end()) { if (_eventIds.find(id) != _eventIds.end()) {
return; return;
} }
@ -1199,11 +1199,11 @@ void InnerWidget::suggestRestrictUser(not_null<UserData*> user) {
Expects(result.type() == mtpc_channels_channelParticipant); Expects(result.type() == mtpc_channels_channelParticipant);
auto &participant = result.c_channels_channelParticipant(); auto &participant = result.c_channels_channelParticipant();
_channel->owner().processUsers(participant.vusers); _channel->owner().processUsers(participant.vusers());
auto type = participant.vparticipant.type(); auto type = participant.vparticipant().type();
if (type == mtpc_channelParticipantBanned) { if (type == mtpc_channelParticipantBanned) {
auto &banned = participant.vparticipant.c_channelParticipantBanned(); auto &banned = participant.vparticipant().c_channelParticipantBanned();
editRestrictions(false, banned.vbanned_rights); editRestrictions(false, banned.vbanned_rights());
} else { } else {
auto hasAdminRights = (type == mtpc_channelParticipantAdmin) auto hasAdminRights = (type == mtpc_channelParticipantAdmin)
|| (type == mtpc_channelParticipantCreator); || (type == mtpc_channelParticipantCreator);
@ -1239,7 +1239,7 @@ void InnerWidget::restrictUser(
void InnerWidget::restrictUserDone(not_null<UserData*> user, const MTPChatBannedRights &rights) { void InnerWidget::restrictUserDone(not_null<UserData*> user, const MTPChatBannedRights &rights) {
Expects(rights.type() == mtpc_chatBannedRights); Expects(rights.type() == mtpc_chatBannedRights);
if (rights.c_chatBannedRights().vflags.v) { if (rights.c_chatBannedRights().vflags().v) {
_admins.erase(std::remove(_admins.begin(), _admins.end(), user), _admins.end()); _admins.erase(std::remove(_admins.begin(), _admins.end(), user), _admins.end());
_adminsCanEdit.erase(std::remove(_adminsCanEdit.begin(), _adminsCanEdit.end(), user), _adminsCanEdit.end()); _adminsCanEdit.erase(std::remove(_adminsCanEdit.begin(), _adminsCanEdit.end(), user), _adminsCanEdit.end());
} }

View file

@ -52,39 +52,44 @@ MTPMessage PrepareLogMessage(
const auto removeFlags = MTPDmessageService::Flag::f_out const auto removeFlags = MTPDmessageService::Flag::f_out
| MTPDmessageService::Flag::f_post | MTPDmessageService::Flag::f_post
/* | MTPDmessageService::Flag::f_reply_to_msg_id*/; /* | MTPDmessageService::Flag::f_reply_to_msg_id*/;
const auto flags = message.vflags.v & ~removeFlags; const auto flags = message.vflags().v & ~removeFlags;
const auto fromId = message.vfrom_id();
return MTP_messageService( return MTP_messageService(
MTP_flags(flags), MTP_flags(flags),
MTP_int(newId), MTP_int(newId),
message.vfrom_id, MTP_int(message.vfrom_id().value_or_empty()),
message.vto_id, message.vto_id(),
message.vreply_to_msg_id, MTP_int(0), // reply_to_msg_id
MTP_int(newDate), MTP_int(newDate),
message.vaction); message.vaction());
}, [&](const MTPDmessage &message) { }, [&](const MTPDmessage &message) {
const auto removeFlags = MTPDmessage::Flag::f_out const auto removeFlags = MTPDmessage::Flag::f_out
| MTPDmessage::Flag::f_post | MTPDmessage::Flag::f_post
| MTPDmessage::Flag::f_reply_to_msg_id | MTPDmessage::Flag::f_reply_to_msg_id
| MTPDmessage::Flag::f_edit_date | MTPDmessage::Flag::f_edit_date
| MTPDmessage::Flag::f_grouped_id; | MTPDmessage::Flag::f_grouped_id;
const auto flags = message.vflags.v & ~removeFlags; const auto flags = message.vflags().v & ~removeFlags;
const auto fwdFrom = message.vfwd_from();
const auto media = message.vmedia();
const auto markup = message.vreply_markup();
const auto entities = message.ventities();
return MTP_message( return MTP_message(
MTP_flags(flags), MTP_flags(flags),
MTP_int(newId), MTP_int(newId),
message.vfrom_id, MTP_int(message.vfrom_id().value_or_empty()),
message.vto_id, message.vto_id(),
message.vfwd_from, fwdFrom ? *fwdFrom : MTPMessageFwdHeader(),
message.vvia_bot_id, MTP_int(message.vvia_bot_id().value_or_empty()),
message.vreply_to_msg_id, MTP_int(0), // reply_to_msg_id
MTP_int(newDate), MTP_int(newDate),
message.vmessage, message.vmessage(),
message.vmedia, media ? *media : MTPMessageMedia(),
message.vreply_markup, markup ? *markup : MTPReplyMarkup(),
message.ventities, entities ? *entities : MTPVector<MTPMessageEntity>(),
message.vviews, MTP_int(message.vviews().value_or_empty()),
message.vedit_date, MTP_int(0), // edit_date
MTP_string(""), MTP_string(),
message.vgrouped_id); MTP_long(0)); // grouped_id
}); });
} }
@ -92,8 +97,9 @@ bool MediaCanHaveCaption(const MTPMessage &message) {
if (message.type() != mtpc_message) { if (message.type() != mtpc_message) {
return false; return false;
} }
auto &data = message.c_message(); const auto &data = message.c_message();
auto mediaType = data.has_media() ? data.vmedia.type() : mtpc_messageMediaEmpty; const auto media = data.vmedia();
const auto mediaType = media ? media->type() : mtpc_messageMediaEmpty;
return (mediaType == mtpc_messageMediaDocument || mediaType == mtpc_messageMediaPhoto); return (mediaType == mtpc_messageMediaDocument || mediaType == mtpc_messageMediaPhoto);
} }
@ -101,12 +107,11 @@ TextWithEntities ExtractEditedText(const MTPMessage &message) {
if (message.type() != mtpc_message) { if (message.type() != mtpc_message) {
return TextWithEntities(); return TextWithEntities();
} }
auto &data = message.c_message(); const auto &data = message.c_message();
auto text = TextUtilities::Clean(qs(data.vmessage)); return {
auto entities = data.has_entities() TextUtilities::Clean(qs(data.vmessage())),
? TextUtilities::EntitiesFromMTP(data.ventities.v) TextUtilities::EntitiesFromMTP(data.ventities().value_or_empty())
: EntitiesInText(); };
return { text, entities };
} }
const auto CollectChanges = [](auto &phraseMap, auto plusFlags, auto minusFlags) { const auto CollectChanges = [](auto &phraseMap, auto plusFlags, auto minusFlags) {
@ -134,8 +139,8 @@ TextWithEntities GenerateAdminChangeText(
using Flag = MTPDchatAdminRights::Flag; using Flag = MTPDchatAdminRights::Flag;
using Flags = MTPDchatAdminRights::Flags; using Flags = MTPDchatAdminRights::Flags;
auto newFlags = newRights ? newRights->c_chatAdminRights().vflags.v : MTPDchatAdminRights::Flags(0); auto newFlags = newRights ? newRights->c_chatAdminRights().vflags().v : MTPDchatAdminRights::Flags(0);
auto prevFlags = prevRights ? prevRights->c_chatAdminRights().vflags.v : MTPDchatAdminRights::Flags(0); auto prevFlags = prevRights ? prevRights->c_chatAdminRights().vflags().v : MTPDchatAdminRights::Flags(0);
auto result = tr::lng_admin_log_promoted(tr::now, lt_user, user, Ui::Text::WithEntities); auto result = tr::lng_admin_log_promoted(tr::now, lt_user, user, Ui::Text::WithEntities);
auto useInviteLinkPhrase = channel->isMegagroup() && channel->anyoneCanAddMembers(); auto useInviteLinkPhrase = channel->isMegagroup() && channel->anyoneCanAddMembers();
@ -177,8 +182,8 @@ QString GenerateBannedChangeText(
using Flag = MTPDchatBannedRights::Flag; using Flag = MTPDchatBannedRights::Flag;
using Flags = MTPDchatBannedRights::Flags; using Flags = MTPDchatBannedRights::Flags;
auto newFlags = newRights ? newRights->c_chatBannedRights().vflags.v : Flags(0); auto newFlags = newRights ? newRights->c_chatBannedRights().vflags().v : Flags(0);
auto prevFlags = prevRights ? prevRights->c_chatBannedRights().vflags.v : Flags(0); auto prevFlags = prevRights ? prevRights->c_chatBannedRights().vflags().v : Flags(0);
static auto phraseMap = std::map<Flags, tr::phrase<>>{ static auto phraseMap = std::map<Flags, tr::phrase<>>{
{ Flag::f_view_messages, tr::lng_admin_log_banned_view_messages }, { Flag::f_view_messages, tr::lng_admin_log_banned_view_messages },
{ Flag::f_send_messages, tr::lng_admin_log_banned_send_messages }, { Flag::f_send_messages, tr::lng_admin_log_banned_send_messages },
@ -202,8 +207,8 @@ TextWithEntities GenerateBannedChangeText(
using Flag = MTPDchatBannedRights::Flag; using Flag = MTPDchatBannedRights::Flag;
using Flags = MTPDchatBannedRights::Flags; using Flags = MTPDchatBannedRights::Flags;
auto newFlags = newRights ? newRights->c_chatBannedRights().vflags.v : Flags(0); auto newFlags = newRights ? newRights->c_chatBannedRights().vflags().v : Flags(0);
auto newUntil = newRights ? newRights->c_chatBannedRights().vuntil_date.v : TimeId(0); auto newUntil = newRights ? newRights->c_chatBannedRights().vuntil_date().v : TimeId(0);
auto indefinitely = ChannelData::IsRestrictedForever(newUntil); auto indefinitely = ChannelData::IsRestrictedForever(newUntil);
if (newFlags & Flag::f_view_messages) { if (newFlags & Flag::f_view_messages) {
return tr::lng_admin_log_banned(tr::now, lt_user, user, Ui::Text::WithEntities); return tr::lng_admin_log_banned(tr::now, lt_user, user, Ui::Text::WithEntities);
@ -268,38 +273,38 @@ auto GenerateParticipantChangeTextInner(
return tr::lng_admin_log_transferred( return tr::lng_admin_log_transferred(
tr::now, tr::now,
lt_user, lt_user,
GenerateUserString(data.vuser_id), GenerateUserString(data.vuser_id()),
Ui::Text::WithEntities); Ui::Text::WithEntities);
}, [&](const MTPDchannelParticipantAdmin &data) { }, [&](const MTPDchannelParticipantAdmin &data) {
auto user = GenerateUserString(data.vuser_id); auto user = GenerateUserString(data.vuser_id());
return GenerateAdminChangeText( return GenerateAdminChangeText(
channel, channel,
user, user,
&data.vadmin_rights, &data.vadmin_rights(),
(oldType == mtpc_channelParticipantAdmin) (oldType == mtpc_channelParticipantAdmin)
? &oldParticipant->c_channelParticipantAdmin().vadmin_rights ? &oldParticipant->c_channelParticipantAdmin().vadmin_rights()
: nullptr); : nullptr);
}, [&](const MTPDchannelParticipantBanned &data) { }, [&](const MTPDchannelParticipantBanned &data) {
auto user = GenerateUserString(data.vuser_id); auto user = GenerateUserString(data.vuser_id());
return GenerateBannedChangeText( return GenerateBannedChangeText(
user, user,
&data.vbanned_rights, &data.vbanned_rights(),
(oldType == mtpc_channelParticipantBanned) (oldType == mtpc_channelParticipantBanned)
? &oldParticipant->c_channelParticipantBanned().vbanned_rights ? &oldParticipant->c_channelParticipantBanned().vbanned_rights()
: nullptr); : nullptr);
}, [&](const auto &data) { }, [&](const auto &data) {
auto user = GenerateUserString(data.vuser_id); auto user = GenerateUserString(data.vuser_id());
if (oldType == mtpc_channelParticipantAdmin) { if (oldType == mtpc_channelParticipantAdmin) {
return GenerateAdminChangeText( return GenerateAdminChangeText(
channel, channel,
user, user,
nullptr, nullptr,
&oldParticipant->c_channelParticipantAdmin().vadmin_rights); &oldParticipant->c_channelParticipantAdmin().vadmin_rights());
} else if (oldType == mtpc_channelParticipantBanned) { } else if (oldType == mtpc_channelParticipantBanned) {
return GenerateBannedChangeText( return GenerateBannedChangeText(
user, user,
nullptr, nullptr,
&oldParticipant->c_channelParticipantBanned().vbanned_rights); &oldParticipant->c_channelParticipantBanned().vbanned_rights());
} }
return tr::lng_admin_log_invited(tr::now, lt_user, user, Ui::Text::WithEntities); return tr::lng_admin_log_invited(tr::now, lt_user, user, Ui::Text::WithEntities);
}); });
@ -364,11 +369,11 @@ void GenerateItems(
Fn<void(OwnedItem item)> callback) { Fn<void(OwnedItem item)> callback) {
Expects(history->peer->isChannel()); Expects(history->peer->isChannel());
auto id = event.vid.v; auto id = event.vid().v;
auto from = Auth().data().user(event.vuser_id.v); auto from = Auth().data().user(event.vuser_id().v);
auto channel = history->peer->asChannel(); auto channel = history->peer->asChannel();
auto &action = event.vaction; auto &action = event.vaction();
auto date = event.vdate.v; auto date = event.vdate().v;
auto addPart = [&](not_null<HistoryItem*> item) { auto addPart = [&](not_null<HistoryItem*> item) {
return callback(OwnedItem(delegate, item)); return callback(OwnedItem(delegate, item));
}; };
@ -392,13 +397,13 @@ void GenerateItems(
lt_from, lt_from,
fromLinkText, fromLinkText,
lt_title, lt_title,
qs(action.vnew_value)); qs(action.vnew_value()));
addSimpleServiceMessage(text); addSimpleServiceMessage(text);
}; };
auto createChangeAbout = [&](const MTPDchannelAdminLogEventActionChangeAbout &action) { auto createChangeAbout = [&](const MTPDchannelAdminLogEventActionChangeAbout &action) {
auto newValue = qs(action.vnew_value); auto newValue = qs(action.vnew_value());
auto oldValue = qs(action.vprev_value); auto oldValue = qs(action.vprev_value());
auto text = (channel->isMegagroup() auto text = (channel->isMegagroup()
? (newValue.isEmpty() ? (newValue.isEmpty()
? tr::lng_admin_log_removed_description_group ? tr::lng_admin_log_removed_description_group
@ -422,8 +427,8 @@ void GenerateItems(
}; };
auto createChangeUsername = [&](const MTPDchannelAdminLogEventActionChangeUsername &action) { auto createChangeUsername = [&](const MTPDchannelAdminLogEventActionChangeUsername &action) {
auto newValue = qs(action.vnew_value); auto newValue = qs(action.vnew_value());
auto oldValue = qs(action.vprev_value); auto oldValue = qs(action.vprev_value());
auto text = (channel->isMegagroup() auto text = (channel->isMegagroup()
? (newValue.isEmpty() ? (newValue.isEmpty()
? tr::lng_admin_log_removed_link_group ? tr::lng_admin_log_removed_link_group
@ -447,7 +452,7 @@ void GenerateItems(
}; };
auto createChangePhoto = [&](const MTPDchannelAdminLogEventActionChangePhoto &action) { auto createChangePhoto = [&](const MTPDchannelAdminLogEventActionChangePhoto &action) {
action.vnew_photo.match([&](const MTPDphoto &data) { action.vnew_photo().match([&](const MTPDphoto &data) {
auto photo = Auth().data().processPhoto(data); auto photo = Auth().data().processPhoto(data);
auto text = (channel->isMegagroup() auto text = (channel->isMegagroup()
? tr::lng_admin_log_changed_photo_group ? tr::lng_admin_log_changed_photo_group
@ -468,7 +473,7 @@ void GenerateItems(
}; };
auto createToggleInvites = [&](const MTPDchannelAdminLogEventActionToggleInvites &action) { auto createToggleInvites = [&](const MTPDchannelAdminLogEventActionToggleInvites &action) {
auto enabled = (action.vnew_value.type() == mtpc_boolTrue); auto enabled = (action.vnew_value().type() == mtpc_boolTrue);
auto text = (enabled auto text = (enabled
? tr::lng_admin_log_invites_enabled ? tr::lng_admin_log_invites_enabled
: tr::lng_admin_log_invites_disabled); : tr::lng_admin_log_invites_disabled);
@ -476,7 +481,7 @@ void GenerateItems(
}; };
auto createToggleSignatures = [&](const MTPDchannelAdminLogEventActionToggleSignatures &action) { auto createToggleSignatures = [&](const MTPDchannelAdminLogEventActionToggleSignatures &action) {
auto enabled = (action.vnew_value.type() == mtpc_boolTrue); auto enabled = (action.vnew_value().type() == mtpc_boolTrue);
auto text = (enabled auto text = (enabled
? tr::lng_admin_log_signatures_enabled ? tr::lng_admin_log_signatures_enabled
: tr::lng_admin_log_signatures_disabled); : tr::lng_admin_log_signatures_disabled);
@ -484,7 +489,7 @@ void GenerateItems(
}; };
auto createUpdatePinned = [&](const MTPDchannelAdminLogEventActionUpdatePinned &action) { auto createUpdatePinned = [&](const MTPDchannelAdminLogEventActionUpdatePinned &action) {
if (action.vmessage.type() == mtpc_messageEmpty) { if (action.vmessage().type() == mtpc_messageEmpty) {
auto text = tr::lng_admin_log_unpinned_message(tr::now, lt_from, fromLinkText); auto text = tr::lng_admin_log_unpinned_message(tr::now, lt_from, fromLinkText);
addSimpleServiceMessage(text); addSimpleServiceMessage(text);
} else { } else {
@ -494,7 +499,7 @@ void GenerateItems(
auto detachExistingItem = false; auto detachExistingItem = false;
addPart(history->createItem( addPart(history->createItem(
PrepareLogMessage( PrepareLogMessage(
action.vmessage, action.vmessage(),
idManager->next(), idManager->next(),
date), date),
detachExistingItem)); detachExistingItem));
@ -502,8 +507,8 @@ void GenerateItems(
}; };
auto createEditMessage = [&](const MTPDchannelAdminLogEventActionEditMessage &action) { auto createEditMessage = [&](const MTPDchannelAdminLogEventActionEditMessage &action) {
auto newValue = ExtractEditedText(action.vnew_message); auto newValue = ExtractEditedText(action.vnew_message());
auto canHaveCaption = MediaCanHaveCaption(action.vnew_message); auto canHaveCaption = MediaCanHaveCaption(action.vnew_message());
auto text = (!canHaveCaption auto text = (!canHaveCaption
? tr::lng_admin_log_edited_message ? tr::lng_admin_log_edited_message
: newValue.text.isEmpty() : newValue.text.isEmpty()
@ -514,11 +519,11 @@ void GenerateItems(
fromLinkText); fromLinkText);
addSimpleServiceMessage(text); addSimpleServiceMessage(text);
auto oldValue = ExtractEditedText(action.vprev_message); auto oldValue = ExtractEditedText(action.vprev_message());
auto detachExistingItem = false; auto detachExistingItem = false;
auto body = history->createItem( auto body = history->createItem(
PrepareLogMessage( PrepareLogMessage(
action.vnew_message, action.vnew_message(),
idManager->next(), idManager->next(),
date), date),
detachExistingItem); detachExistingItem);
@ -541,7 +546,7 @@ void GenerateItems(
auto detachExistingItem = false; auto detachExistingItem = false;
addPart(history->createItem( addPart(history->createItem(
PrepareLogMessage(action.vmessage, idManager->next(), date), PrepareLogMessage(action.vmessage(), idManager->next(), date),
detachExistingItem)); detachExistingItem));
}; };
@ -563,7 +568,7 @@ void GenerateItems(
auto bodyFlags = Flag::f_entities | Flag::f_from_id; auto bodyFlags = Flag::f_entities | Flag::f_from_id;
auto bodyReplyTo = 0; auto bodyReplyTo = 0;
auto bodyViaBotId = 0; auto bodyViaBotId = 0;
auto bodyText = GenerateParticipantChangeText(channel, action.vparticipant); auto bodyText = GenerateParticipantChangeText(channel, action.vparticipant());
addPart(history->owner().makeMessage(history, idManager->next(), bodyFlags, bodyReplyTo, bodyViaBotId, date, peerToUser(from->id), QString(), bodyText)); addPart(history->owner().makeMessage(history, idManager->next(), bodyFlags, bodyReplyTo, bodyViaBotId, date, peerToUser(from->id), QString(), bodyText));
}; };
@ -571,13 +576,13 @@ void GenerateItems(
auto bodyFlags = Flag::f_entities | Flag::f_from_id; auto bodyFlags = Flag::f_entities | Flag::f_from_id;
auto bodyReplyTo = 0; auto bodyReplyTo = 0;
auto bodyViaBotId = 0; auto bodyViaBotId = 0;
auto bodyText = GenerateParticipantChangeText(channel, action.vnew_participant, &action.vprev_participant); auto bodyText = GenerateParticipantChangeText(channel, action.vnew_participant(), &action.vprev_participant());
addPart(history->owner().makeMessage(history, idManager->next(), bodyFlags, bodyReplyTo, bodyViaBotId, date, peerToUser(from->id), QString(), bodyText)); addPart(history->owner().makeMessage(history, idManager->next(), bodyFlags, bodyReplyTo, bodyViaBotId, date, peerToUser(from->id), QString(), bodyText));
}; };
auto createParticipantToggleAdmin = [&](const MTPDchannelAdminLogEventActionParticipantToggleAdmin &action) { auto createParticipantToggleAdmin = [&](const MTPDchannelAdminLogEventActionParticipantToggleAdmin &action) {
if (action.vnew_participant.type() == mtpc_channelParticipantAdmin if (action.vnew_participant().type() == mtpc_channelParticipantAdmin
&& action.vprev_participant.type() == mtpc_channelParticipantCreator) { && action.vprev_participant().type() == mtpc_channelParticipantCreator) {
// In case of ownership transfer we show that message in // In case of ownership transfer we show that message in
// the "User > Creator" part and skip the "Creator > Admin" part. // the "User > Creator" part and skip the "Creator > Admin" part.
return; return;
@ -585,12 +590,12 @@ void GenerateItems(
auto bodyFlags = Flag::f_entities | Flag::f_from_id; auto bodyFlags = Flag::f_entities | Flag::f_from_id;
auto bodyReplyTo = 0; auto bodyReplyTo = 0;
auto bodyViaBotId = 0; auto bodyViaBotId = 0;
auto bodyText = GenerateParticipantChangeText(channel, action.vnew_participant, &action.vprev_participant); auto bodyText = GenerateParticipantChangeText(channel, action.vnew_participant(), &action.vprev_participant());
addPart(history->owner().makeMessage(history, idManager->next(), bodyFlags, bodyReplyTo, bodyViaBotId, date, peerToUser(from->id), QString(), bodyText)); addPart(history->owner().makeMessage(history, idManager->next(), bodyFlags, bodyReplyTo, bodyViaBotId, date, peerToUser(from->id), QString(), bodyText));
}; };
auto createChangeStickerSet = [&](const MTPDchannelAdminLogEventActionChangeStickerSet &action) { auto createChangeStickerSet = [&](const MTPDchannelAdminLogEventActionChangeStickerSet &action) {
auto set = action.vnew_stickerset; auto set = action.vnew_stickerset();
auto removed = (set.type() == mtpc_inputStickerSetEmpty); auto removed = (set.type() == mtpc_inputStickerSetEmpty);
if (removed) { if (removed) {
auto text = tr::lng_admin_log_removed_stickers_group(tr::now, lt_from, fromLinkText); auto text = tr::lng_admin_log_removed_stickers_group(tr::now, lt_from, fromLinkText);
@ -615,7 +620,7 @@ void GenerateItems(
}; };
auto createTogglePreHistoryHidden = [&](const MTPDchannelAdminLogEventActionTogglePreHistoryHidden &action) { auto createTogglePreHistoryHidden = [&](const MTPDchannelAdminLogEventActionTogglePreHistoryHidden &action) {
auto hidden = (action.vnew_value.type() == mtpc_boolTrue); auto hidden = (action.vnew_value().type() == mtpc_boolTrue);
auto text = (hidden auto text = (hidden
? tr::lng_admin_log_history_made_hidden ? tr::lng_admin_log_history_made_hidden
: tr::lng_admin_log_history_made_visible); : tr::lng_admin_log_history_made_visible);
@ -626,7 +631,7 @@ void GenerateItems(
auto bodyFlags = Flag::f_entities | Flag::f_from_id; auto bodyFlags = Flag::f_entities | Flag::f_from_id;
auto bodyReplyTo = 0; auto bodyReplyTo = 0;
auto bodyViaBotId = 0; auto bodyViaBotId = 0;
auto bodyText = GenerateDefaultBannedRightsChangeText(channel, action.vnew_banned_rights, action.vprev_banned_rights); auto bodyText = GenerateDefaultBannedRightsChangeText(channel, action.vnew_banned_rights(), action.vprev_banned_rights());
addPart(history->owner().makeMessage(history, idManager->next(), bodyFlags, bodyReplyTo, bodyViaBotId, date, peerToUser(from->id), QString(), bodyText)); addPart(history->owner().makeMessage(history, idManager->next(), bodyFlags, bodyReplyTo, bodyViaBotId, date, peerToUser(from->id), QString(), bodyText));
}; };
@ -636,14 +641,14 @@ void GenerateItems(
auto detachExistingItem = false; auto detachExistingItem = false;
addPart(history->createItem( addPart(history->createItem(
PrepareLogMessage(action.vmessage, idManager->next(), date), PrepareLogMessage(action.vmessage(), idManager->next(), date),
detachExistingItem)); detachExistingItem));
}; };
auto createChangeLinkedChat = [&](const MTPDchannelAdminLogEventActionChangeLinkedChat &action) { auto createChangeLinkedChat = [&](const MTPDchannelAdminLogEventActionChangeLinkedChat &action) {
const auto broadcast = channel->isBroadcast(); const auto broadcast = channel->isBroadcast();
const auto was = history->owner().channelLoaded(action.vprev_value.v); const auto was = history->owner().channelLoaded(action.vprev_value().v);
const auto now = history->owner().channelLoaded(action.vnew_value.v); const auto now = history->owner().channelLoaded(action.vnew_value().v);
if (!now) { if (!now) {
auto text = (broadcast auto text = (broadcast
? tr::lng_admin_log_removed_linked_chat ? tr::lng_admin_log_removed_linked_chat
@ -672,9 +677,9 @@ void GenerateItems(
}; };
auto createChangeLocation = [&](const MTPDchannelAdminLogEventActionChangeLocation &action) { auto createChangeLocation = [&](const MTPDchannelAdminLogEventActionChangeLocation &action) {
action.vnew_value.match([&](const MTPDchannelLocation &data) { action.vnew_value().match([&](const MTPDchannelLocation &data) {
const auto address = qs(data.vaddress); const auto address = qs(data.vaddress());
const auto link = data.vgeo_point.match([&](const MTPDgeoPoint &data) { const auto link = data.vgeo_point().match([&](const MTPDgeoPoint &data) {
return textcmdLink( return textcmdLink(
LocationClickHandler::Url(Data::LocationPoint(data)), LocationClickHandler::Url(Data::LocationPoint(data)),
address); address);

View file

@ -374,27 +374,27 @@ bool History::updateSendActionNeedsAnimating(
emplaceAction( emplaceAction(
Type::UploadVideo, Type::UploadVideo,
kStatusShowClientsideUploadVideo, kStatusShowClientsideUploadVideo,
data.vprogress.v); data.vprogress().v);
}, [&](const MTPDsendMessageUploadAudioAction &data) { }, [&](const MTPDsendMessageUploadAudioAction &data) {
emplaceAction( emplaceAction(
Type::UploadVoice, Type::UploadVoice,
kStatusShowClientsideUploadVoice, kStatusShowClientsideUploadVoice,
data.vprogress.v); data.vprogress().v);
}, [&](const MTPDsendMessageUploadRoundAction &data) { }, [&](const MTPDsendMessageUploadRoundAction &data) {
emplaceAction( emplaceAction(
Type::UploadRound, Type::UploadRound,
kStatusShowClientsideUploadRound, kStatusShowClientsideUploadRound,
data.vprogress.v); data.vprogress().v);
}, [&](const MTPDsendMessageUploadPhotoAction &data) { }, [&](const MTPDsendMessageUploadPhotoAction &data) {
emplaceAction( emplaceAction(
Type::UploadPhoto, Type::UploadPhoto,
kStatusShowClientsideUploadPhoto, kStatusShowClientsideUploadPhoto,
data.vprogress.v); data.vprogress().v);
}, [&](const MTPDsendMessageUploadDocumentAction &data) { }, [&](const MTPDsendMessageUploadDocumentAction &data) {
emplaceAction( emplaceAction(
Type::UploadFile, Type::UploadFile,
kStatusShowClientsideUploadFile, kStatusShowClientsideUploadFile,
data.vprogress.v); data.vprogress().v);
}, [&](const MTPDsendMessageGamePlayAction &) { }, [&](const MTPDsendMessageGamePlayAction &) {
const auto i = _sendActions.find(user); const auto i = _sendActions.find(user);
if ((i == end(_sendActions)) if ((i == end(_sendActions))
@ -587,10 +587,7 @@ HistoryItem *History::createItem(
result->removeMainView(); result->removeMainView();
} }
if (message.type() == mtpc_message) { if (message.type() == mtpc_message) {
const auto media = message.c_message().has_media() result->updateSentMedia(message.c_message().vmedia());
? &message.c_message().vmedia
: nullptr;
result->updateSentMedia(media);
} }
return result; return result;
} }
@ -838,9 +835,9 @@ void History::addUnreadMentionsSlice(const MTPmessages_Messages &result) {
auto count = 0; auto count = 0;
auto messages = (const QVector<MTPMessage>*)nullptr; auto messages = (const QVector<MTPMessage>*)nullptr;
auto getMessages = [&](auto &list) { auto getMessages = [&](auto &list) {
owner().processUsers(list.vusers); owner().processUsers(list.vusers());
owner().processChats(list.vchats); owner().processChats(list.vchats());
return &list.vmessages.v; return &list.vmessages().v;
}; };
switch (result.type()) { switch (result.type()) {
case mtpc_messages_messages: { case mtpc_messages_messages: {
@ -852,14 +849,14 @@ void History::addUnreadMentionsSlice(const MTPmessages_Messages &result) {
case mtpc_messages_messagesSlice: { case mtpc_messages_messagesSlice: {
auto &d = result.c_messages_messagesSlice(); auto &d = result.c_messages_messagesSlice();
messages = getMessages(d); messages = getMessages(d);
count = d.vcount.v; count = d.vcount().v;
} break; } break;
case mtpc_messages_channelMessages: { case mtpc_messages_channelMessages: {
LOG(("API Error: unexpected messages.channelMessages! (History::addUnreadMentionsSlice)")); LOG(("API Error: unexpected messages.channelMessages! (History::addUnreadMentionsSlice)"));
auto &d = result.c_messages_channelMessages(); auto &d = result.c_messages_channelMessages();
messages = getMessages(d); messages = getMessages(d);
count = d.vcount.v; count = d.vcount().v;
} break; } break;
case mtpc_messages_messagesNotModified: { case mtpc_messages_messagesNotModified: {
@ -1019,14 +1016,14 @@ void History::applyMessageChanges(
void History::applyServiceChanges( void History::applyServiceChanges(
not_null<HistoryItem*> item, not_null<HistoryItem*> item,
const MTPDmessageService &data) { const MTPDmessageService &data) {
auto &action = data.vaction; auto &action = data.vaction();
switch (action.type()) { switch (action.type()) {
case mtpc_messageActionChatAddUser: { case mtpc_messageActionChatAddUser: {
auto &d = action.c_messageActionChatAddUser(); auto &d = action.c_messageActionChatAddUser();
if (const auto megagroup = peer->asMegagroup()) { if (const auto megagroup = peer->asMegagroup()) {
const auto mgInfo = megagroup->mgInfo.get(); const auto mgInfo = megagroup->mgInfo.get();
Assert(mgInfo != nullptr); Assert(mgInfo != nullptr);
for (const auto &userId : d.vusers.v) { for (const auto &userId : d.vusers().v) {
if (const auto user = owner().userLoaded(userId.v)) { if (const auto user = owner().userLoaded(userId.v)) {
if (!base::contains(mgInfo->lastParticipants, user)) { if (!base::contains(mgInfo->lastParticipants, user)) {
mgInfo->lastParticipants.push_front(user); mgInfo->lastParticipants.push_front(user);
@ -1073,7 +1070,7 @@ void History::applyServiceChanges(
case mtpc_messageActionChatDeleteUser: { case mtpc_messageActionChatDeleteUser: {
auto &d = action.c_messageActionChatDeleteUser(); auto &d = action.c_messageActionChatDeleteUser();
auto uid = d.vuser_id.v; auto uid = d.vuser_id().v;
if (lastKeyboardFrom == peerFromUser(uid)) { if (lastKeyboardFrom == peerFromUser(uid)) {
clearLastKeyboard(); clearLastKeyboard();
} }
@ -1114,8 +1111,8 @@ void History::applyServiceChanges(
case mtpc_messageActionChatEditPhoto: { case mtpc_messageActionChatEditPhoto: {
auto &d = action.c_messageActionChatEditPhoto(); auto &d = action.c_messageActionChatEditPhoto();
d.vphoto.match([&](const MTPDphoto &data) { d.vphoto().match([&](const MTPDphoto &data) {
const auto &sizes = data.vsizes.v; const auto &sizes = data.vsizes().v;
if (!sizes.isEmpty()) { if (!sizes.isEmpty()) {
auto photo = owner().processPhoto(data); auto photo = owner().processPhoto(data);
photo->peer = peer; photo->peer = peer;
@ -1124,18 +1121,18 @@ void History::applyServiceChanges(
const MTPFileLocation *smallLoc = nullptr; const MTPFileLocation *smallLoc = nullptr;
const MTPFileLocation *bigLoc = nullptr; const MTPFileLocation *bigLoc = nullptr;
switch (smallSize.type()) { switch (smallSize.type()) {
case mtpc_photoSize: smallLoc = &smallSize.c_photoSize().vlocation; break; case mtpc_photoSize: smallLoc = &smallSize.c_photoSize().vlocation(); break;
case mtpc_photoCachedSize: smallLoc = &smallSize.c_photoCachedSize().vlocation; break; case mtpc_photoCachedSize: smallLoc = &smallSize.c_photoCachedSize().vlocation(); break;
} }
switch (bigSize.type()) { switch (bigSize.type()) {
case mtpc_photoSize: bigLoc = &bigSize.c_photoSize().vlocation; break; case mtpc_photoSize: bigLoc = &bigSize.c_photoSize().vlocation(); break;
case mtpc_photoCachedSize: bigLoc = &bigSize.c_photoCachedSize().vlocation; break; case mtpc_photoCachedSize: bigLoc = &bigSize.c_photoCachedSize().vlocation(); break;
} }
if (smallLoc && bigLoc) { if (smallLoc && bigLoc) {
if (const auto chat = peer->asChat()) { if (const auto chat = peer->asChat()) {
chat->setPhoto(photo->id, MTP_chatPhoto(*smallLoc, *bigLoc, data.vdc_id)); chat->setPhoto(photo->id, MTP_chatPhoto(*smallLoc, *bigLoc, data.vdc_id()));
} else if (const auto channel = peer->asChannel()) { } else if (const auto channel = peer->asChannel()) {
channel->setPhoto(photo->id, MTP_chatPhoto(*smallLoc, *bigLoc, data.vdc_id)); channel->setPhoto(photo->id, MTP_chatPhoto(*smallLoc, *bigLoc, data.vdc_id()));
} }
peer->loadUserpic(); peer->loadUserpic();
} }
@ -1152,7 +1149,7 @@ void History::applyServiceChanges(
case mtpc_messageActionChatEditTitle: { case mtpc_messageActionChatEditTitle: {
auto &d = action.c_messageActionChatEditTitle(); auto &d = action.c_messageActionChatEditTitle();
if (auto chat = peer->asChat()) { if (auto chat = peer->asChat()) {
chat->setName(qs(d.vtitle)); chat->setName(qs(d.vtitle()));
} }
} break; } break;
@ -1160,7 +1157,7 @@ void History::applyServiceChanges(
if (const auto chat = peer->asChat()) { if (const auto chat = peer->asChat()) {
chat->addFlags(MTPDchat::Flag::f_deactivated); chat->addFlags(MTPDchat::Flag::f_deactivated);
const auto &d = action.c_messageActionChatMigrateTo(); const auto &d = action.c_messageActionChatMigrateTo();
if (const auto channel = owner().channelLoaded(d.vchannel_id.v)) { if (const auto channel = owner().channelLoaded(d.vchannel_id().v)) {
Data::ApplyMigration(chat, channel); Data::ApplyMigration(chat, channel);
} }
} }
@ -1170,15 +1167,17 @@ void History::applyServiceChanges(
if (const auto channel = peer->asChannel()) { if (const auto channel = peer->asChannel()) {
channel->addFlags(MTPDchannel::Flag::f_megagroup); channel->addFlags(MTPDchannel::Flag::f_megagroup);
const auto &d = action.c_messageActionChannelMigrateFrom(); const auto &d = action.c_messageActionChannelMigrateFrom();
if (const auto chat = owner().chatLoaded(d.vchat_id.v)) { if (const auto chat = owner().chatLoaded(d.vchat_id().v)) {
Data::ApplyMigration(chat, channel); Data::ApplyMigration(chat, channel);
} }
} }
} break; } break;
case mtpc_messageActionPinMessage: { case mtpc_messageActionPinMessage: {
if (data.has_reply_to_msg_id() && item) { if (const auto replyToMsgId = data.vreply_to_msg_id()) {
item->history()->peer->setPinnedMessageId(data.vreply_to_msg_id.v); if (item) {
item->history()->peer->setPinnedMessageId(replyToMsgId->v);
}
} }
} break; } break;
@ -1848,7 +1847,7 @@ void History::setFolderPointer(Data::Folder *folder) {
} }
void History::applyPinnedUpdate(const MTPDupdateDialogPinned &data) { void History::applyPinnedUpdate(const MTPDupdateDialogPinned &data) {
const auto folderId = data.has_folder_id() ? data.vfolder_id.v : 0; const auto folderId = data.vfolder_id().value_or_empty();
if (!folderKnown()) { if (!folderKnown()) {
if (folderId) { if (folderId) {
setFolder(owner().folder(folderId)); setFolder(owner().folder(folderId));
@ -2401,9 +2400,9 @@ void History::setFakeChatListMessageFrom(const MTPmessages_Messages &data) {
const MTPDmessages_messagesNotModified &) { const MTPDmessages_messagesNotModified &) {
return static_cast<const MTPMessage*>(nullptr); return static_cast<const MTPMessage*>(nullptr);
}, [&](const auto &data) { }, [&](const auto &data) {
for (const auto &message : data.vmessages.v) { for (const auto &message : data.vmessages().v) {
const auto id = message.match([](const auto &data) { const auto id = message.match([](const auto &data) {
return data.vid.v; return data.vid().v;
}); });
if (id != last->id) { if (id != last->id) {
return &message; return &message;
@ -2500,27 +2499,28 @@ bool History::isServerSideUnread(not_null<const HistoryItem*> item) const {
void History::applyDialog( void History::applyDialog(
Data::Folder *requestFolder, Data::Folder *requestFolder,
const MTPDdialog &data) { const MTPDdialog &data) {
const auto folder = data.has_folder_id() const auto folderId = data.vfolder_id();
? (data.vfolder_id.v const auto folder = !folderId
? owner().folder(data.vfolder_id.v).get() ? requestFolder
: nullptr) : folderId->v
: requestFolder; ? owner().folder(folderId->v).get()
: nullptr;
applyDialogFields( applyDialogFields(
folder, folder,
data.vunread_count.v, data.vunread_count().v,
data.vread_inbox_max_id.v, data.vread_inbox_max_id().v,
data.vread_outbox_max_id.v); data.vread_outbox_max_id().v);
applyDialogTopMessage(data.vtop_message.v); applyDialogTopMessage(data.vtop_message().v);
setUnreadMark(data.is_unread_mark()); setUnreadMark(data.is_unread_mark());
setUnreadMentionsCount(data.vunread_mentions_count.v); setUnreadMentionsCount(data.vunread_mentions_count().v);
if (const auto channel = peer->asChannel()) { if (const auto channel = peer->asChannel()) {
if (data.has_pts()) { if (const auto pts = data.vpts()) {
channel->ptsReceived(data.vpts.v); channel->ptsReceived(pts->v);
} }
if (!channel->amCreator()) { if (!channel->amCreator()) {
const auto topMessageId = FullMsgId( const auto topMessageId = FullMsgId(
peerToChannel(channel->id), peerToChannel(channel->id),
data.vtop_message.v); data.vtop_message().v);
if (const auto item = owner().message(topMessageId)) { if (const auto item = owner().message(topMessageId)) {
if (item->date() <= channel->date) { if (item->date() <= channel->date) {
session().api().requestSelfParticipant(channel); session().api().requestSelfParticipant(channel);
@ -2529,11 +2529,12 @@ void History::applyDialog(
} }
} }
owner().applyNotifySetting( owner().applyNotifySetting(
MTP_notifyPeer(data.vpeer), MTP_notifyPeer(data.vpeer()),
data.vnotify_settings); data.vnotify_settings());
if (data.has_draft() && data.vdraft.type() == mtpc_draftMessage) { const auto draft = data.vdraft();
Data::applyPeerCloudDraft(peer->id, data.vdraft.c_draftMessage()); if (draft && draft->type() == mtpc_draftMessage) {
Data::applyPeerCloudDraft(peer->id, draft->c_draftMessage());
} }
session().api().dialogEntryApplied(this); session().api().dialogEntryApplied(this);
} }

View file

@ -88,47 +88,49 @@ MediaCheckResult CheckMessageMedia(const MTPMessageMedia &media) {
}, [](const MTPDmessageMediaContact &) { }, [](const MTPDmessageMediaContact &) {
return Result::Good; return Result::Good;
}, [](const MTPDmessageMediaGeo &data) { }, [](const MTPDmessageMediaGeo &data) {
return data.vgeo.match([](const MTPDgeoPoint &) { return data.vgeo().match([](const MTPDgeoPoint &) {
return Result::Good; return Result::Good;
}, [](const MTPDgeoPointEmpty &) { }, [](const MTPDgeoPointEmpty &) {
return Result::Empty; return Result::Empty;
}); });
}, [](const MTPDmessageMediaVenue &data) { }, [](const MTPDmessageMediaVenue &data) {
return data.vgeo.match([](const MTPDgeoPoint &) { return data.vgeo().match([](const MTPDgeoPoint &) {
return Result::Good; return Result::Good;
}, [](const MTPDgeoPointEmpty &) { }, [](const MTPDgeoPointEmpty &) {
return Result::Empty; return Result::Empty;
}); });
}, [](const MTPDmessageMediaGeoLive &data) { }, [](const MTPDmessageMediaGeoLive &data) {
return data.vgeo.match([](const MTPDgeoPoint &) { return data.vgeo().match([](const MTPDgeoPoint &) {
return Result::Good; return Result::Good;
}, [](const MTPDgeoPointEmpty &) { }, [](const MTPDgeoPointEmpty &) {
return Result::Empty; return Result::Empty;
}); });
}, [](const MTPDmessageMediaPhoto &data) { }, [](const MTPDmessageMediaPhoto &data) {
if (data.has_ttl_seconds()) { const auto photo = data.vphoto();
if (data.vttl_seconds()) {
return Result::HasTimeToLive; return Result::HasTimeToLive;
} else if (!data.has_photo()) { } else if (!photo) {
return Result::Empty; return Result::Empty;
} }
return data.vphoto.match([](const MTPDphoto &) { return photo->match([](const MTPDphoto &) {
return Result::Good; return Result::Good;
}, [](const MTPDphotoEmpty &) { }, [](const MTPDphotoEmpty &) {
return Result::Empty; return Result::Empty;
}); });
}, [](const MTPDmessageMediaDocument &data) { }, [](const MTPDmessageMediaDocument &data) {
if (data.has_ttl_seconds()) { const auto document = data.vdocument();
if (data.vttl_seconds()) {
return Result::HasTimeToLive; return Result::HasTimeToLive;
} else if (!data.has_document()) { } else if (!document) {
return Result::Empty; return Result::Empty;
} }
return data.vdocument.match([](const MTPDdocument &) { return document->match([](const MTPDdocument &) {
return Result::Good; return Result::Good;
}, [](const MTPDdocumentEmpty &) { }, [](const MTPDdocumentEmpty &) {
return Result::Empty; return Result::Empty;
}); });
}, [](const MTPDmessageMediaWebPage &data) { }, [](const MTPDmessageMediaWebPage &data) {
return data.vwebpage.match([](const MTPDwebPage &) { return data.vwebpage().match([](const MTPDwebPage &) {
return Result::Good; return Result::Good;
}, [](const MTPDwebPageEmpty &) { }, [](const MTPDwebPageEmpty &) {
return Result::Good; return Result::Good;
@ -138,7 +140,7 @@ MediaCheckResult CheckMessageMedia(const MTPMessageMedia &media) {
return Result::Unsupported; return Result::Unsupported;
}); });
}, [](const MTPDmessageMediaGame &data) { }, [](const MTPDmessageMediaGame &data) {
return data.vgame.match([](const MTPDgame &) { return data.vgame().match([](const MTPDgame &) {
return Result::Good; return Result::Good;
}); });
}, [](const MTPDmessageMediaInvoice &) { }, [](const MTPDmessageMediaInvoice &) {
@ -814,35 +816,36 @@ not_null<HistoryItem*> HistoryItem::Create(
not_null<History*> history, not_null<History*> history,
const MTPMessage &message) { const MTPMessage &message) {
return message.match([&](const MTPDmessage &data) -> HistoryItem* { return message.match([&](const MTPDmessage &data) -> HistoryItem* {
const auto checked = data.has_media() const auto media = data.vmedia();
? CheckMessageMedia(data.vmedia) const auto checked = media
? CheckMessageMedia(*media)
: MediaCheckResult::Good; : MediaCheckResult::Good;
if (checked == MediaCheckResult::Unsupported) { if (checked == MediaCheckResult::Unsupported) {
return CreateUnsupportedMessage( return CreateUnsupportedMessage(
history, history,
data.vid.v, data.vid().v,
data.vflags.v, data.vflags().v,
data.vreply_to_msg_id.v, data.vreply_to_msg_id().value_or_empty(),
data.vvia_bot_id.v, data.vvia_bot_id().value_or_empty(),
data.vdate.v, data.vdate().v,
data.vfrom_id.v); data.vfrom_id().value_or_empty());
} else if (checked == MediaCheckResult::Empty) { } else if (checked == MediaCheckResult::Empty) {
const auto text = HistoryService::PreparedText { const auto text = HistoryService::PreparedText {
tr::lng_message_empty(tr::now) tr::lng_message_empty(tr::now)
}; };
return history->owner().makeServiceMessage( return history->owner().makeServiceMessage(
history, history,
data.vid.v, data.vid().v,
data.vdate.v, data.vdate().v,
text, text,
data.vflags.v, data.vflags().v,
data.has_from_id() ? data.vfrom_id.v : UserId(0)); data.vfrom_id().value_or_empty());
} else if (checked == MediaCheckResult::HasTimeToLive) { } else if (checked == MediaCheckResult::HasTimeToLive) {
return history->owner().makeServiceMessage(history, data); return history->owner().makeServiceMessage(history, data);
} }
return history->owner().makeMessage(history, data); return history->owner().makeMessage(history, data);
}, [&](const MTPDmessageService &data) -> HistoryItem* { }, [&](const MTPDmessageService &data) -> HistoryItem* {
if (data.vaction.type() == mtpc_messageActionPhoneCall) { if (data.vaction().type() == mtpc_messageActionPhoneCall) {
return history->owner().makeMessage(history, data); return history->owner().makeMessage(history, data);
} }
return history->owner().makeServiceMessage(history, data); return history->owner().makeServiceMessage(history, data);
@ -850,6 +853,6 @@ not_null<HistoryItem*> HistoryItem::Create(
const auto text = HistoryService::PreparedText{ const auto text = HistoryService::PreparedText{
tr::lng_message_empty(tr::now) tr::lng_message_empty(tr::now)
}; };
return history->owner().makeServiceMessage(history, data.vid.v, TimeId(0), text); return history->owner().makeServiceMessage(history, data.vid().v, TimeId(0), text);
}); });
} }

View file

@ -777,46 +777,46 @@ void HistoryMessageReplyMarkup::createFromButtonRows(
for (const auto &row : list) { for (const auto &row : list) {
row.match([&](const MTPDkeyboardButtonRow &data) { row.match([&](const MTPDkeyboardButtonRow &data) {
auto row = std::vector<Button>(); auto row = std::vector<Button>();
row.reserve(data.vbuttons.v.size()); row.reserve(data.vbuttons().v.size());
for (const auto &button : data.vbuttons.v) { for (const auto &button : data.vbuttons().v) {
using Type = Button::Type; using Type = Button::Type;
button.match([&](const MTPDkeyboardButton &data) { button.match([&](const MTPDkeyboardButton &data) {
row.emplace_back(Type::Default, qs(data.vtext)); row.emplace_back(Type::Default, qs(data.vtext()));
}, [&](const MTPDkeyboardButtonCallback &data) { }, [&](const MTPDkeyboardButtonCallback &data) {
row.emplace_back( row.emplace_back(
Type::Callback, Type::Callback,
qs(data.vtext), qs(data.vtext()),
qba(data.vdata)); qba(data.vdata()));
}, [&](const MTPDkeyboardButtonRequestGeoLocation &data) { }, [&](const MTPDkeyboardButtonRequestGeoLocation &data) {
row.emplace_back(Type::RequestLocation, qs(data.vtext)); row.emplace_back(Type::RequestLocation, qs(data.vtext()));
}, [&](const MTPDkeyboardButtonRequestPhone &data) { }, [&](const MTPDkeyboardButtonRequestPhone &data) {
row.emplace_back(Type::RequestPhone, qs(data.vtext)); row.emplace_back(Type::RequestPhone, qs(data.vtext()));
}, [&](const MTPDkeyboardButtonUrl &data) { }, [&](const MTPDkeyboardButtonUrl &data) {
row.emplace_back( row.emplace_back(
Type::Url, Type::Url,
qs(data.vtext), qs(data.vtext()),
qba(data.vurl)); qba(data.vurl()));
}, [&](const MTPDkeyboardButtonSwitchInline &data) { }, [&](const MTPDkeyboardButtonSwitchInline &data) {
const auto type = data.is_same_peer() const auto type = data.is_same_peer()
? Type::SwitchInlineSame ? Type::SwitchInlineSame
: Type::SwitchInline; : Type::SwitchInline;
row.emplace_back(type, qs(data.vtext), qba(data.vquery)); row.emplace_back(type, qs(data.vtext()), qba(data.vquery()));
if (type == Type::SwitchInline) { if (type == Type::SwitchInline) {
// Optimization flag. // Optimization flag.
// Fast check on all new messages if there is a switch button to auto-click it. // Fast check on all new messages if there is a switch button to auto-click it.
flags |= MTPDreplyKeyboardMarkup_ClientFlag::f_has_switch_inline_button; flags |= MTPDreplyKeyboardMarkup_ClientFlag::f_has_switch_inline_button;
} }
}, [&](const MTPDkeyboardButtonGame &data) { }, [&](const MTPDkeyboardButtonGame &data) {
row.emplace_back(Type::Game, qs(data.vtext)); row.emplace_back(Type::Game, qs(data.vtext()));
}, [&](const MTPDkeyboardButtonBuy &data) { }, [&](const MTPDkeyboardButtonBuy &data) {
row.emplace_back(Type::Buy, qs(data.vtext)); row.emplace_back(Type::Buy, qs(data.vtext()));
}, [&](const MTPDkeyboardButtonUrlAuth &data) { }, [&](const MTPDkeyboardButtonUrlAuth &data) {
row.emplace_back( row.emplace_back(
Type::Auth, Type::Auth,
qs(data.vtext), qs(data.vtext()),
qba(data.vurl), qba(data.vurl()),
data.has_fwd_text() ? qs(data.vfwd_text) : QString(), qs(data.vfwd_text().value_or_empty()),
data.vbutton_id.v); data.vbutton_id().v);
}, [&](const MTPDinputKeyboardButtonUrlAuth &data) { }, [&](const MTPDinputKeyboardButtonUrlAuth &data) {
LOG(("API Error: inputKeyboardButtonUrlAuth received.")); LOG(("API Error: inputKeyboardButtonUrlAuth received."));
// Should not get those for the users. // Should not get those for the users.
@ -837,26 +837,26 @@ void HistoryMessageReplyMarkup::create(const MTPReplyMarkup &markup) {
switch (markup.type()) { switch (markup.type()) {
case mtpc_replyKeyboardMarkup: { case mtpc_replyKeyboardMarkup: {
auto &d = markup.c_replyKeyboardMarkup(); auto &d = markup.c_replyKeyboardMarkup();
flags = d.vflags.v; flags = d.vflags().v;
createFromButtonRows(d.vrows.v); createFromButtonRows(d.vrows().v);
} break; } break;
case mtpc_replyInlineMarkup: { case mtpc_replyInlineMarkup: {
auto &d = markup.c_replyInlineMarkup(); auto &d = markup.c_replyInlineMarkup();
flags = MTPDreplyKeyboardMarkup::Flags(0) | MTPDreplyKeyboardMarkup_ClientFlag::f_inline; flags = MTPDreplyKeyboardMarkup::Flags(0) | MTPDreplyKeyboardMarkup_ClientFlag::f_inline;
createFromButtonRows(d.vrows.v); createFromButtonRows(d.vrows().v);
} break; } break;
case mtpc_replyKeyboardHide: { case mtpc_replyKeyboardHide: {
auto &d = markup.c_replyKeyboardHide(); auto &d = markup.c_replyKeyboardHide();
flags = mtpCastFlags(d.vflags) | MTPDreplyKeyboardMarkup_ClientFlag::f_zero; flags = mtpCastFlags(d.vflags()) | MTPDreplyKeyboardMarkup_ClientFlag::f_zero;
} break; } break;
case mtpc_replyKeyboardForceReply: { case mtpc_replyKeyboardForceReply: {
auto &d = markup.c_replyKeyboardForceReply(); auto &d = markup.c_replyKeyboardForceReply();
flags = mtpCastFlags(d.vflags) | MTPDreplyKeyboardMarkup_ClientFlag::f_force_reply; flags = mtpCastFlags(d.vflags()) | MTPDreplyKeyboardMarkup_ClientFlag::f_force_reply;
} break; } break;
} }
} }

View file

@ -317,18 +317,20 @@ struct HistoryMessage::CreateConfig {
void HistoryMessage::FillForwardedInfo( void HistoryMessage::FillForwardedInfo(
CreateConfig &config, CreateConfig &config,
const MTPDmessageFwdHeader &data) { const MTPDmessageFwdHeader &data) {
config.originalDate = data.vdate.v; if (const auto channelId = data.vchannel_id()) {
if (data.has_from_id() || data.has_channel_id()) { config.senderOriginal = peerFromChannel(*channelId);
config.senderOriginal = data.has_channel_id() } else if (const auto fromId = data.vfrom_id()) {
? peerFromChannel(data.vchannel_id) config.senderOriginal = peerFromUser(*fromId);
: peerFromUser(data.vfrom_id);
} }
if (data.has_from_name()) config.senderNameOriginal = qs(data.vfrom_name); config.originalDate = data.vdate().v;
if (data.has_channel_post()) config.originalId = data.vchannel_post.v; config.senderNameOriginal = qs(data.vfrom_name().value_or_empty());
if (data.has_post_author()) config.authorOriginal = qs(data.vpost_author); config.originalId = data.vchannel_post().value_or_empty();
if (data.has_saved_from_peer() && data.has_saved_from_msg_id()) { config.authorOriginal = qs(data.vpost_author().value_or_empty());
config.savedFromPeer = peerFromMTP(data.vsaved_from_peer); const auto savedFromPeer = data.vsaved_from_peer();
config.savedFromMsgId = data.vsaved_from_msg_id.v; const auto savedFromMsgId = data.vsaved_from_msg_id();
if (savedFromPeer && savedFromMsgId) {
config.savedFromPeer = peerFromMTP(*savedFromPeer);
config.savedFromMsgId = savedFromMsgId->v;
} }
} }
@ -337,39 +339,35 @@ HistoryMessage::HistoryMessage(
const MTPDmessage &data) const MTPDmessage &data)
: HistoryItem( : HistoryItem(
history, history,
data.vid.v, data.vid().v,
data.vflags.v, data.vflags().v,
data.vdate.v, data.vdate().v,
data.has_from_id() ? data.vfrom_id.v : UserId(0)) { data.vfrom_id().value_or_empty()) {
auto config = CreateConfig(); auto config = CreateConfig();
if (const auto forwarded = data.vfwd_from()) {
if (data.has_fwd_from()) { forwarded->match([&](const MTPDmessageFwdHeader &data) {
data.vfwd_from.match([&](const MTPDmessageFwdHeader &data) {
FillForwardedInfo(config, data); FillForwardedInfo(config, data);
}); });
} }
if (data.has_reply_to_msg_id()) config.replyTo = data.vreply_to_msg_id.v; config.replyTo = data.vreply_to_msg_id().value_or_empty();
if (data.has_via_bot_id()) config.viaBotId = data.vvia_bot_id.v; config.viaBotId = data.vvia_bot_id().value_or_empty();
if (data.has_views()) config.viewsCount = data.vviews.v; config.viewsCount = data.vviews().value_or(-1);
if (data.has_reply_markup()) config.mtpMarkup = &data.vreply_markup; config.mtpMarkup = data.vreply_markup();
if (data.has_edit_date()) config.editDate = data.vedit_date.v; config.editDate = data.vedit_date().value_or_empty();
if (data.has_post_author()) config.author = qs(data.vpost_author); config.author = qs(data.vpost_author().value_or_empty());
createComponents(config); createComponents(config);
if (data.has_media()) { if (const auto media = data.vmedia()) {
setMedia(data.vmedia); setMedia(*media);
} }
setText({
auto text = TextUtilities::Clean(qs(data.vmessage)); TextUtilities::Clean(qs(data.vmessage())),
auto entities = data.has_entities() TextUtilities::EntitiesFromMTP(data.ventities().value_or_empty())
? TextUtilities::EntitiesFromMTP(data.ventities.v) });
: EntitiesInText(); if (const auto groupedId = data.vgrouped_id()) {
setText({ text, entities });
if (data.has_grouped_id()) {
setGroupId( setGroupId(
MessageGroupId::FromRaw(history->peer->id, data.vgrouped_id.v)); MessageGroupId::FromRaw(history->peer->id, groupedId->v));
} }
} }
@ -378,21 +376,21 @@ HistoryMessage::HistoryMessage(
const MTPDmessageService &data) const MTPDmessageService &data)
: HistoryItem( : HistoryItem(
history, history,
data.vid.v, data.vid().v,
mtpCastFlags(data.vflags.v), mtpCastFlags(data.vflags().v),
data.vdate.v, data.vdate().v,
data.has_from_id() ? data.vfrom_id.v : UserId(0)) { data.vfrom_id().value_or_empty()) {
auto config = CreateConfig(); auto config = CreateConfig();
if (data.has_reply_to_msg_id()) config.replyTo = data.vreply_to_msg_id.v; config.replyTo = data.vreply_to_msg_id().value_or_empty();
createComponents(config); createComponents(config);
switch (data.vaction.type()) { switch (data.vaction().type()) {
case mtpc_messageActionPhoneCall: { case mtpc_messageActionPhoneCall: {
_media = std::make_unique<Data::MediaCall>( _media = std::make_unique<Data::MediaCall>(
this, this,
data.vaction.c_messageActionPhoneCall()); data.vaction().c_messageActionPhoneCall());
} break; } break;
default: Unexpected("Service message action type in HistoryMessage."); default: Unexpected("Service message action type in HistoryMessage.");
@ -450,9 +448,10 @@ HistoryMessage::HistoryMessage(
if (flags & MTPDmessage::Flag::f_post_author) { if (flags & MTPDmessage::Flag::f_post_author) {
config.author = postAuthor; config.author = postAuthor;
} }
auto fwdViaBot = original->viaBot(); if (const auto fwdViaBot = original->viaBot()) {
if (fwdViaBot) config.viaBotId = peerToUser(fwdViaBot->id); config.viaBotId = peerToUser(fwdViaBot->id);
int fwdViewsCount = original->viewsCount(); }
const auto fwdViewsCount = original->viewsCount();
if (fwdViewsCount > 0) { if (fwdViewsCount > 0) {
config.viewsCount = fwdViewsCount; config.viewsCount = fwdViewsCount;
} else if (isPost() } else if (isPost()
@ -672,7 +671,7 @@ void HistoryMessage::createComponents(const CreateConfig &config) {
if (config.mtpMarkup) { if (config.mtpMarkup) {
// optimization: don't create markup component for the case // optimization: don't create markup component for the case
// MTPDreplyKeyboardHide with flags = 0, assume it has f_zero flag // MTPDreplyKeyboardHide with flags = 0, assume it has f_zero flag
if (config.mtpMarkup->type() != mtpc_replyKeyboardHide || config.mtpMarkup->c_replyKeyboardHide().vflags.v != 0) { if (config.mtpMarkup->type() != mtpc_replyKeyboardHide || config.mtpMarkup->c_replyKeyboardHide().vflags().v != 0) {
mask |= HistoryMessageReplyMarkup::Bit(); mask |= HistoryMessageReplyMarkup::Bit();
} }
} else if (config.inlineMarkup) { } else if (config.inlineMarkup) {
@ -783,12 +782,12 @@ std::unique_ptr<Data::Media> HistoryMessage::CreateMedia(
return media.match([&](const MTPDmessageMediaContact &media) -> Result { return media.match([&](const MTPDmessageMediaContact &media) -> Result {
return std::make_unique<Data::MediaContact>( return std::make_unique<Data::MediaContact>(
item, item,
media.vuser_id.v, media.vuser_id().v,
qs(media.vfirst_name), qs(media.vfirst_name()),
qs(media.vlast_name), qs(media.vlast_name()),
qs(media.vphone_number)); qs(media.vphone_number()));
}, [&](const MTPDmessageMediaGeo &media) -> Result { }, [&](const MTPDmessageMediaGeo &media) -> Result {
return media.vgeo.match([&](const MTPDgeoPoint &point) -> Result { return media.vgeo().match([&](const MTPDgeoPoint &point) -> Result {
return std::make_unique<Data::MediaLocation>( return std::make_unique<Data::MediaLocation>(
item, item,
Data::LocationPoint(point)); Data::LocationPoint(point));
@ -796,7 +795,7 @@ std::unique_ptr<Data::Media> HistoryMessage::CreateMedia(
return nullptr; return nullptr;
}); });
}, [&](const MTPDmessageMediaGeoLive &media) -> Result { }, [&](const MTPDmessageMediaGeoLive &media) -> Result {
return media.vgeo.match([&](const MTPDgeoPoint &point) -> Result { return media.vgeo().match([&](const MTPDgeoPoint &point) -> Result {
return std::make_unique<Data::MediaLocation>( return std::make_unique<Data::MediaLocation>(
item, item,
Data::LocationPoint(point)); Data::LocationPoint(point));
@ -804,28 +803,29 @@ std::unique_ptr<Data::Media> HistoryMessage::CreateMedia(
return nullptr; return nullptr;
}); });
}, [&](const MTPDmessageMediaVenue &media) -> Result { }, [&](const MTPDmessageMediaVenue &media) -> Result {
return media.vgeo.match([&](const MTPDgeoPoint &point) -> Result { return media.vgeo().match([&](const MTPDgeoPoint &point) -> Result {
return std::make_unique<Data::MediaLocation>( return std::make_unique<Data::MediaLocation>(
item, item,
Data::LocationPoint(point), Data::LocationPoint(point),
qs(media.vtitle), qs(media.vtitle()),
qs(media.vaddress)); qs(media.vaddress()));
}, [](const MTPDgeoPointEmpty &data) -> Result { }, [](const MTPDgeoPointEmpty &data) -> Result {
return nullptr; return nullptr;
}); });
}, [&](const MTPDmessageMediaPhoto &media) -> Result { }, [&](const MTPDmessageMediaPhoto &media) -> Result {
if (media.has_ttl_seconds()) { const auto photo = media.vphoto();
if (media.vttl_seconds()) {
LOG(("App Error: " LOG(("App Error: "
"Unexpected MTPMessageMediaPhoto " "Unexpected MTPMessageMediaPhoto "
"with ttl_seconds in HistoryMessage.")); "with ttl_seconds in HistoryMessage."));
return nullptr; return nullptr;
} else if (!media.has_photo()) { } else if (!photo) {
LOG(("API Error: " LOG(("API Error: "
"Got MTPMessageMediaPhoto " "Got MTPMessageMediaPhoto "
"without photo and without ttl_seconds.")); "without photo and without ttl_seconds."));
return nullptr; return nullptr;
} }
return media.vphoto.match([&](const MTPDphoto &photo) -> Result { return photo->match([&](const MTPDphoto &photo) -> Result {
return std::make_unique<Data::MediaPhoto>( return std::make_unique<Data::MediaPhoto>(
item, item,
item->history()->owner().processPhoto(photo)); item->history()->owner().processPhoto(photo));
@ -833,19 +833,19 @@ std::unique_ptr<Data::Media> HistoryMessage::CreateMedia(
return nullptr; return nullptr;
}); });
}, [&](const MTPDmessageMediaDocument &media) -> Result { }, [&](const MTPDmessageMediaDocument &media) -> Result {
if (media.has_ttl_seconds()) { const auto document = media.vdocument();
if (media.vttl_seconds()) {
LOG(("App Error: " LOG(("App Error: "
"Unexpected MTPMessageMediaDocument " "Unexpected MTPMessageMediaDocument "
"with ttl_seconds in HistoryMessage.")); "with ttl_seconds in HistoryMessage."));
return nullptr; return nullptr;
} else if (!media.has_document()) { } else if (!document) {
LOG(("API Error: " LOG(("API Error: "
"Got MTPMessageMediaDocument " "Got MTPMessageMediaDocument "
"without document and without ttl_seconds.")); "without document and without ttl_seconds."));
return nullptr; return nullptr;
} }
const auto &document = media.vdocument; return document->match([&](const MTPDdocument &document) -> Result {
return document.match([&](const MTPDdocument &document) -> Result {
return std::make_unique<Data::MediaFile>( return std::make_unique<Data::MediaFile>(
item, item,
item->history()->owner().processDocument(document)); item->history()->owner().processDocument(document));
@ -853,7 +853,7 @@ std::unique_ptr<Data::Media> HistoryMessage::CreateMedia(
return nullptr; return nullptr;
}); });
}, [&](const MTPDmessageMediaWebPage &media) { }, [&](const MTPDmessageMediaWebPage &media) {
return media.vwebpage.match([](const MTPDwebPageEmpty &) -> Result { return media.vwebpage().match([](const MTPDwebPageEmpty &) -> Result {
return nullptr; return nullptr;
}, [&](const MTPDwebPagePending &webpage) -> Result { }, [&](const MTPDwebPagePending &webpage) -> Result {
return std::make_unique<Data::MediaWebPage>( return std::make_unique<Data::MediaWebPage>(
@ -869,7 +869,7 @@ std::unique_ptr<Data::Media> HistoryMessage::CreateMedia(
return nullptr; return nullptr;
}); });
}, [&](const MTPDmessageMediaGame &media) -> Result { }, [&](const MTPDmessageMediaGame &media) -> Result {
return media.vgame.match([&](const MTPDgame &game) { return media.vgame().match([&](const MTPDgame &game) {
return std::make_unique<Data::MediaGame>( return std::make_unique<Data::MediaGame>(
item, item,
item->history()->owner().processGame(game)); item->history()->owner().processGame(game));
@ -909,31 +909,31 @@ void HistoryMessage::applyEdition(const MTPDmessage &message) {
// } // }
//} //}
if (message.has_edit_date()) { if (const auto editDate = message.vedit_date()) {
_flags |= MTPDmessage::Flag::f_edit_date; _flags |= MTPDmessage::Flag::f_edit_date;
if (!Has<HistoryMessageEdited>()) { if (!Has<HistoryMessageEdited>()) {
AddComponents(HistoryMessageEdited::Bit()); AddComponents(HistoryMessageEdited::Bit());
} }
auto edited = Get<HistoryMessageEdited>(); auto edited = Get<HistoryMessageEdited>();
edited->date = message.vedit_date.v; edited->date = editDate->v;
} }
TextWithEntities textWithEntities = { qs(message.vmessage), EntitiesInText() }; const auto textWithEntities = TextWithEntities{
if (message.has_entities()) { qs(message.vmessage()),
textWithEntities.entities = TextUtilities::EntitiesFromMTP(message.ventities.v); TextUtilities::EntitiesFromMTP(message.ventities().value_or_empty())
} };
setReplyMarkup(message.has_reply_markup() ? (&message.vreply_markup) : nullptr); setReplyMarkup(message.vreply_markup());
if (!isLocalUpdateMedia()) { if (!isLocalUpdateMedia()) {
refreshMedia(message.has_media() ? (&message.vmedia) : nullptr); refreshMedia(message.vmedia());
} }
setViewsCount(message.has_views() ? message.vviews.v : -1); setViewsCount(message.vviews().value_or(-1));
setText(textWithEntities); setText(textWithEntities);
finishEdition(keyboardTop); finishEdition(keyboardTop);
} }
void HistoryMessage::applyEdition(const MTPDmessageService &message) { void HistoryMessage::applyEdition(const MTPDmessageService &message) {
if (message.vaction.type() == mtpc_messageActionHistoryClear) { if (message.vaction().type() == mtpc_messageActionHistoryClear) {
setReplyMarkup(nullptr); setReplyMarkup(nullptr);
refreshMedia(nullptr); refreshMedia(nullptr);
setEmptyText(); setEmptyText();
@ -1059,7 +1059,7 @@ void HistoryMessage::setReplyMarkup(const MTPReplyMarkup *markup) {
// optimization: don't create markup component for the case // optimization: don't create markup component for the case
// MTPDreplyKeyboardHide with flags = 0, assume it has f_zero flag // MTPDreplyKeyboardHide with flags = 0, assume it has f_zero flag
if (markup->type() == mtpc_replyKeyboardHide && markup->c_replyKeyboardHide().vflags.v == 0) { if (markup->type() == mtpc_replyKeyboardHide && markup->c_replyKeyboardHide().vflags().v == 0) {
bool changed = false; bool changed = false;
if (Has<HistoryMessageReplyMarkup>()) { if (Has<HistoryMessageReplyMarkup>()) {
RemoveComponents(HistoryMessageReplyMarkup::Bit()); RemoveComponents(HistoryMessageReplyMarkup::Bit());

View file

@ -37,7 +37,7 @@ constexpr auto kPinnedMessageTextLimit = 16;
void HistoryService::setMessageByAction(const MTPmessageAction &action) { void HistoryService::setMessageByAction(const MTPmessageAction &action) {
auto prepareChatAddUserText = [this](const MTPDmessageActionChatAddUser &action) { auto prepareChatAddUserText = [this](const MTPDmessageActionChatAddUser &action) {
auto result = PreparedText{}; auto result = PreparedText{};
auto &users = action.vusers.v; auto &users = action.vusers().v;
if (users.size() == 1) { if (users.size() == 1) {
auto u = history()->owner().user(users[0].v); auto u = history()->owner().user(users[0].v);
if (u == _from) { if (u == _from) {
@ -81,7 +81,7 @@ void HistoryService::setMessageByAction(const MTPmessageAction &action) {
auto prepareChatCreate = [this](const MTPDmessageActionChatCreate &action) { auto prepareChatCreate = [this](const MTPDmessageActionChatCreate &action) {
auto result = PreparedText{}; auto result = PreparedText{};
result.links.push_back(fromLink()); result.links.push_back(fromLink());
result.text = tr::lng_action_created_chat(tr::now, lt_from, fromLinkText(), lt_title, TextUtilities::Clean(qs(action.vtitle))); result.text = tr::lng_action_created_chat(tr::now, lt_from, fromLinkText(), lt_title, TextUtilities::Clean(qs(action.vtitle())));
return result; return result;
}; };
@ -91,7 +91,7 @@ void HistoryService::setMessageByAction(const MTPmessageAction &action) {
result.text = tr::lng_action_created_channel(tr::now); result.text = tr::lng_action_created_channel(tr::now);
} else { } else {
result.links.push_back(fromLink()); result.links.push_back(fromLink());
result.text = tr::lng_action_created_chat(tr::now, lt_from, fromLinkText(), lt_title, TextUtilities::Clean(qs(action.vtitle))); result.text = tr::lng_action_created_chat(tr::now, lt_from, fromLinkText(), lt_title, TextUtilities::Clean(qs(action.vtitle())));
} }
return result; return result;
}; };
@ -109,11 +109,11 @@ void HistoryService::setMessageByAction(const MTPmessageAction &action) {
auto prepareChatDeleteUser = [this](const MTPDmessageActionChatDeleteUser &action) { auto prepareChatDeleteUser = [this](const MTPDmessageActionChatDeleteUser &action) {
auto result = PreparedText{}; auto result = PreparedText{};
if (peerFromUser(action.vuser_id) == _from->id) { if (peerFromUser(action.vuser_id()) == _from->id) {
result.links.push_back(fromLink()); result.links.push_back(fromLink());
result.text = tr::lng_action_user_left(tr::now, lt_from, fromLinkText()); result.text = tr::lng_action_user_left(tr::now, lt_from, fromLinkText());
} else { } else {
auto user = history()->owner().user(action.vuser_id.v); auto user = history()->owner().user(action.vuser_id().v);
result.links.push_back(fromLink()); result.links.push_back(fromLink());
result.links.push_back(user->createOpenLink()); result.links.push_back(user->createOpenLink());
result.text = tr::lng_action_kick_user(tr::now, lt_from, fromLinkText(), lt_user, textcmdLink(2, user->name)); result.text = tr::lng_action_kick_user(tr::now, lt_from, fromLinkText(), lt_user, textcmdLink(2, user->name));
@ -135,10 +135,10 @@ void HistoryService::setMessageByAction(const MTPmessageAction &action) {
auto prepareChatEditTitle = [this](const MTPDmessageActionChatEditTitle &action) { auto prepareChatEditTitle = [this](const MTPDmessageActionChatEditTitle &action) {
auto result = PreparedText{}; auto result = PreparedText{};
if (isPost()) { if (isPost()) {
result.text = tr::lng_action_changed_title_channel(tr::now, lt_title, TextUtilities::Clean(qs(action.vtitle))); result.text = tr::lng_action_changed_title_channel(tr::now, lt_title, TextUtilities::Clean(qs(action.vtitle())));
} else { } else {
result.links.push_back(fromLink()); result.links.push_back(fromLink());
result.text = tr::lng_action_changed_title(tr::now, lt_from, fromLinkText(), lt_title, TextUtilities::Clean(qs(action.vtitle))); result.text = tr::lng_action_changed_title(tr::now, lt_from, fromLinkText(), lt_title, TextUtilities::Clean(qs(action.vtitle())));
} }
return result; return result;
}; };
@ -156,13 +156,13 @@ void HistoryService::setMessageByAction(const MTPmessageAction &action) {
auto prepareCustomAction = [&](const MTPDmessageActionCustomAction &action) { auto prepareCustomAction = [&](const MTPDmessageActionCustomAction &action) {
auto result = PreparedText{}; auto result = PreparedText{};
result.text = qs(action.vmessage); result.text = qs(action.vmessage());
return result; return result;
}; };
auto prepareBotAllowed = [&](const MTPDmessageActionBotAllowed &action) { auto prepareBotAllowed = [&](const MTPDmessageActionBotAllowed &action) {
auto result = PreparedText{}; auto result = PreparedText{};
const auto domain = qs(action.vdomain); const auto domain = qs(action.vdomain());
result.text = tr::lng_action_bot_allowed_from_domain( result.text = tr::lng_action_bot_allowed_from_domain(
tr::now, tr::now,
lt_domain, lt_domain,
@ -173,7 +173,7 @@ void HistoryService::setMessageByAction(const MTPmessageAction &action) {
auto prepareSecureValuesSent = [&](const MTPDmessageActionSecureValuesSent &action) { auto prepareSecureValuesSent = [&](const MTPDmessageActionSecureValuesSent &action) {
auto result = PreparedText{}; auto result = PreparedText{};
auto documents = QStringList(); auto documents = QStringList();
for (const auto &type : action.vtypes.v) { for (const auto &type : action.vtypes().v) {
documents.push_back([&] { documents.push_back([&] {
switch (type.type()) { switch (type.type()) {
case mtpc_secureValueTypePersonalDetails: case mtpc_secureValueTypePersonalDetails:
@ -277,7 +277,7 @@ void HistoryService::applyAction(const MTPMessageAction &action) {
action.match([&](const MTPDmessageActionChatAddUser &data) { action.match([&](const MTPDmessageActionChatAddUser &data) {
if (const auto channel = history()->peer->asMegagroup()) { if (const auto channel = history()->peer->asMegagroup()) {
const auto selfUserId = history()->session().userId(); const auto selfUserId = history()->session().userId();
for (const auto &item : data.vusers.v) { for (const auto &item : data.vusers().v) {
if (item.v == selfUserId) { if (item.v == selfUserId) {
channel->mgInfo->joinedMessageFound = true; channel->mgInfo->joinedMessageFound = true;
break; break;
@ -291,7 +291,7 @@ void HistoryService::applyAction(const MTPMessageAction &action) {
} }
} }
}, [&](const MTPDmessageActionChatEditPhoto &data) { }, [&](const MTPDmessageActionChatEditPhoto &data) {
data.vphoto.match([&](const MTPDphoto &photo) { data.vphoto().match([&](const MTPDphoto &photo) {
_media = std::make_unique<Data::MediaPhoto>( _media = std::make_unique<Data::MediaPhoto>(
this, this,
history()->peer, history()->peer,
@ -498,12 +498,12 @@ HistoryService::PreparedText HistoryService::preparePaymentSentText() {
HistoryService::HistoryService( HistoryService::HistoryService(
not_null<History*> history, not_null<History*> history,
const MTPDmessage &data) const MTPDmessage &data)
: HistoryItem( : HistoryItem(
history, history,
data.vid.v, data.vid().v,
data.vflags.v, data.vflags().v,
data.vdate.v, data.vdate().v,
data.has_from_id() ? data.vfrom_id.v : UserId(0)) { data.vfrom_id().value_or_empty()) {
createFromMtp(data); createFromMtp(data);
} }
@ -512,10 +512,10 @@ HistoryService::HistoryService(
const MTPDmessageService &data) const MTPDmessageService &data)
: HistoryItem( : HistoryItem(
history, history,
data.vid.v, data.vid().v,
mtpCastFlags(data.vflags.v), mtpCastFlags(data.vflags().v),
data.vdate.v, data.vdate().v,
data.has_from_id() ? data.vfrom_id.v : UserId(0)) { data.vfrom_id().value_or_empty()) {
createFromMtp(data); createFromMtp(data);
} }
@ -613,13 +613,18 @@ crl::time HistoryService::getSelfDestructIn(crl::time now) {
} }
void HistoryService::createFromMtp(const MTPDmessage &message) { void HistoryService::createFromMtp(const MTPDmessage &message) {
auto mediaType = message.vmedia.type(); const auto media = message.vmedia();
Assert(media != nullptr);
const auto mediaType = media->type();
switch (mediaType) { switch (mediaType) {
case mtpc_messageMediaPhoto: { case mtpc_messageMediaPhoto: {
if (message.is_media_unread()) { if (message.is_media_unread()) {
auto &photo = message.vmedia.c_messageMediaPhoto(); const auto &photo = media->c_messageMediaPhoto();
Assert(photo.has_ttl_seconds()); const auto ttl = photo.vttl_seconds();
setSelfDestruct(HistoryServiceSelfDestruct::Type::Photo, photo.vttl_seconds.v); Assert(ttl != nullptr);
setSelfDestruct(HistoryServiceSelfDestruct::Type::Photo, ttl->v);
if (out()) { if (out()) {
setServiceText({ tr::lng_ttl_photo_sent(tr::now) }); setServiceText({ tr::lng_ttl_photo_sent(tr::now) });
} else { } else {
@ -634,9 +639,11 @@ void HistoryService::createFromMtp(const MTPDmessage &message) {
} break; } break;
case mtpc_messageMediaDocument: { case mtpc_messageMediaDocument: {
if (message.is_media_unread()) { if (message.is_media_unread()) {
auto &document = message.vmedia.c_messageMediaDocument(); const auto &document = media->c_messageMediaDocument();
Assert(document.has_ttl_seconds()); const auto ttl = document.vttl_seconds();
setSelfDestruct(HistoryServiceSelfDestruct::Type::Video, document.vttl_seconds.v); Assert(ttl != nullptr);
setSelfDestruct(HistoryServiceSelfDestruct::Type::Video, ttl->v);
if (out()) { if (out()) {
setServiceText({ tr::lng_ttl_video_sent(tr::now) }); setServiceText({ tr::lng_ttl_video_sent(tr::now) });
} else { } else {
@ -655,21 +662,21 @@ void HistoryService::createFromMtp(const MTPDmessage &message) {
} }
void HistoryService::createFromMtp(const MTPDmessageService &message) { void HistoryService::createFromMtp(const MTPDmessageService &message) {
if (message.vaction.type() == mtpc_messageActionGameScore) { if (message.vaction().type() == mtpc_messageActionGameScore) {
UpdateComponents(HistoryServiceGameScore::Bit()); UpdateComponents(HistoryServiceGameScore::Bit());
Get<HistoryServiceGameScore>()->score = message.vaction.c_messageActionGameScore().vscore.v; Get<HistoryServiceGameScore>()->score = message.vaction().c_messageActionGameScore().vscore().v;
} else if (message.vaction.type() == mtpc_messageActionPaymentSent) { } else if (message.vaction().type() == mtpc_messageActionPaymentSent) {
UpdateComponents(HistoryServicePayment::Bit()); UpdateComponents(HistoryServicePayment::Bit());
auto amount = message.vaction.c_messageActionPaymentSent().vtotal_amount.v; auto amount = message.vaction().c_messageActionPaymentSent().vtotal_amount().v;
auto currency = qs(message.vaction.c_messageActionPaymentSent().vcurrency); auto currency = qs(message.vaction().c_messageActionPaymentSent().vcurrency());
Get<HistoryServicePayment>()->amount = FillAmountAndCurrency(amount, currency); Get<HistoryServicePayment>()->amount = FillAmountAndCurrency(amount, currency);
} }
if (message.has_reply_to_msg_id()) { if (const auto replyToMsgId = message.vreply_to_msg_id()) {
if (message.vaction.type() == mtpc_messageActionPinMessage) { if (message.vaction().type() == mtpc_messageActionPinMessage) {
UpdateComponents(HistoryServicePinned::Bit()); UpdateComponents(HistoryServicePinned::Bit());
} }
if (auto dependent = GetDependentData()) { if (const auto dependent = GetDependentData()) {
dependent->msgId = message.vreply_to_msg_id.v; dependent->msgId = replyToMsgId->v;
if (!updateDependent()) { if (!updateDependent()) {
history()->session().api().requestMessageData( history()->session().api().requestMessageData(
history()->peer->asChannel(), history()->peer->asChannel(),
@ -678,7 +685,7 @@ void HistoryService::createFromMtp(const MTPDmessageService &message) {
} }
} }
} }
setMessageByAction(message.vaction); setMessageByAction(message.vaction());
} }
void HistoryService::applyEdition(const MTPDmessageService &message) { void HistoryService::applyEdition(const MTPDmessageService &message) {
@ -687,7 +694,7 @@ void HistoryService::applyEdition(const MTPDmessageService &message) {
createFromMtp(message); createFromMtp(message);
if (message.vaction.type() == mtpc_messageActionHistoryClear) { if (message.vaction().type() == mtpc_messageActionHistoryClear) {
removeMedia(); removeMedia();
finishEditionToEmpty(); finishEditionToEmpty();
} else { } else {

View file

@ -2213,29 +2213,29 @@ void HistoryWidget::messagesReceived(PeerData *peer, const MTPmessages_Messages
switch (messages.type()) { switch (messages.type()) {
case mtpc_messages_messages: { case mtpc_messages_messages: {
auto &d(messages.c_messages_messages()); auto &d(messages.c_messages_messages());
_history->owner().processUsers(d.vusers); _history->owner().processUsers(d.vusers());
_history->owner().processChats(d.vchats); _history->owner().processChats(d.vchats());
histList = &d.vmessages.v; histList = &d.vmessages().v;
count = histList->size(); count = histList->size();
} break; } break;
case mtpc_messages_messagesSlice: { case mtpc_messages_messagesSlice: {
auto &d(messages.c_messages_messagesSlice()); auto &d(messages.c_messages_messagesSlice());
_history->owner().processUsers(d.vusers); _history->owner().processUsers(d.vusers());
_history->owner().processChats(d.vchats); _history->owner().processChats(d.vchats());
histList = &d.vmessages.v; histList = &d.vmessages().v;
count = d.vcount.v; count = d.vcount().v;
} break; } break;
case mtpc_messages_channelMessages: { case mtpc_messages_channelMessages: {
auto &d(messages.c_messages_channelMessages()); auto &d(messages.c_messages_channelMessages());
if (peer && peer->isChannel()) { if (peer && peer->isChannel()) {
peer->asChannel()->ptsReceived(d.vpts.v); peer->asChannel()->ptsReceived(d.vpts().v);
} else { } else {
LOG(("API Error: received messages.channelMessages when no channel was passed! (HistoryWidget::messagesReceived)")); LOG(("API Error: received messages.channelMessages when no channel was passed! (HistoryWidget::messagesReceived)"));
} }
_history->owner().processUsers(d.vusers); _history->owner().processUsers(d.vusers());
_history->owner().processChats(d.vchats); _history->owner().processChats(d.vchats());
histList = &d.vmessages.v; histList = &d.vmessages().v;
count = d.vcount.v; count = d.vcount().v;
} break; } break;
case mtpc_messages_messagesNotModified: { case mtpc_messages_messagesNotModified: {
LOG(("API Error: received messages.messagesNotModified! (HistoryWidget::messagesReceived)")); LOG(("API Error: received messages.messagesNotModified! (HistoryWidget::messagesReceived)"));
@ -3289,22 +3289,22 @@ void HistoryWidget::botCallbackDone(
} }
} }
answer.match([&](const MTPDmessages_botCallbackAnswer &data) { answer.match([&](const MTPDmessages_botCallbackAnswer &data) {
if (data.has_message()) { if (const auto message = data.vmessage()) {
if (data.is_alert()) { if (data.is_alert()) {
Ui::show(Box<InformBox>(qs(data.vmessage))); Ui::show(Box<InformBox>(qs(*message)));
} else { } else {
Ui::Toast::Show(qs(data.vmessage)); Ui::Toast::Show(qs(*message));
} }
} else if (data.has_url()) { } else if (const auto url = data.vurl()) {
auto url = qs(data.vurl); auto link = qs(*url);
if (info.game) { if (info.game) {
url = AppendShareGameScoreUrl(url, info.msgId); link = AppendShareGameScoreUrl(link, info.msgId);
BotGameUrlClickHandler(info.bot, url).onClick({}); BotGameUrlClickHandler(info.bot, link).onClick({});
if (item) { if (item) {
updateSendAction(item->history(), SendAction::Type::PlayGame); updateSendAction(item->history(), SendAction::Type::PlayGame);
} }
} else { } else {
UrlClickHandler(url).onClick({}); UrlClickHandler(link).onClick({});
} }
} }
}); });
@ -3449,7 +3449,7 @@ void HistoryWidget::inlineBotResolveDone(
const auto &data = result.c_contacts_resolvedPeer(); const auto &data = result.c_contacts_resolvedPeer();
// Notify::inlineBotRequesting(false); // Notify::inlineBotRequesting(false);
const auto resolvedBot = [&]() -> UserData* { const auto resolvedBot = [&]() -> UserData* {
if (const auto result = session().data().processUsers(data.vusers)) { if (const auto result = session().data().processUsers(data.vusers())) {
if (result->botInfo if (result->botInfo
&& !result->botInfo->inlinePlaceholder.isEmpty()) { && !result->botInfo->inlinePlaceholder.isEmpty()) {
return result; return result;
@ -3457,7 +3457,7 @@ void HistoryWidget::inlineBotResolveDone(
} }
return nullptr; return nullptr;
}(); }();
session().data().processChats(data.vchats); session().data().processChats(data.vchats());
const auto query = ParseInlineBotQuery(_field); const auto query = ParseInlineBotQuery(_field);
if (_inlineBotUsername == query.username) { if (_inlineBotUsername == query.username) {
@ -5888,7 +5888,7 @@ void HistoryWidget::checkPreview() {
MTPmessages_GetWebPagePreview( MTPmessages_GetWebPagePreview(
MTP_flags(0), MTP_flags(0),
MTP_string(_previewLinks), MTP_string(_previewLinks),
MTPnullEntities), MTPVector<MTPMessageEntity>()),
rpcDone(&HistoryWidget::gotPreview, _previewLinks)); rpcDone(&HistoryWidget::gotPreview, _previewLinks));
} else if (i.value()) { } else if (i.value()) {
_previewData = session().data().webpage(i.value()); _previewData = session().data().webpage(i.value());
@ -5910,7 +5910,7 @@ void HistoryWidget::requestPreview() {
MTPmessages_GetWebPagePreview( MTPmessages_GetWebPagePreview(
MTP_flags(0), MTP_flags(0),
MTP_string(_previewLinks), MTP_string(_previewLinks),
MTPnullEntities), MTPVector<MTPMessageEntity>()),
rpcDone(&HistoryWidget::gotPreview, _previewLinks)); rpcDone(&HistoryWidget::gotPreview, _previewLinks));
} }
@ -5919,7 +5919,7 @@ void HistoryWidget::gotPreview(QString links, const MTPMessageMedia &result, mtp
_previewRequest = 0; _previewRequest = 0;
} }
if (result.type() == mtpc_messageMediaWebPage) { if (result.type() == mtpc_messageMediaWebPage) {
const auto &data = result.c_messageMediaWebPage().vwebpage; const auto &data = result.c_messageMediaWebPage().vwebpage();
const auto page = session().data().processWebpage(data); const auto page = session().data().processWebpage(data);
_previewCache.insert(links, page->id); _previewCache.insert(links, page->id);
if (page->pendingTill > 0 && page->pendingTill <= unixtime()) { if (page->pendingTill > 0 && page->pendingTill <= unixtime()) {

View file

@ -99,7 +99,7 @@ void ListController::loadMoreRows() {
_preloadGroupId = 0; _preloadGroupId = 0;
_allLoaded = true; _allLoaded = true;
const auto &chats = result.match([](const auto &data) { const auto &chats = result.match([](const auto &data) {
return data.vchats.v; return data.vchats().v;
}); });
if (!chats.empty()) { if (!chats.empty()) {
for (const auto &chat : chats) { for (const auto &chat : chats) {

View file

@ -25,9 +25,9 @@ namespace {
QString GetContentUrl(const MTPWebDocument &document) { QString GetContentUrl(const MTPWebDocument &document) {
switch (document.type()) { switch (document.type()) {
case mtpc_webDocument: case mtpc_webDocument:
return qs(document.c_webDocument().vurl); return qs(document.c_webDocument().vurl());
case mtpc_webDocumentNoProxy: case mtpc_webDocumentNoProxy:
return qs(document.c_webDocumentNoProxy().vurl); return qs(document.c_webDocumentNoProxy().vurl());
} }
Unexpected("Type in GetContentUrl."); Unexpected("Type in GetContentUrl.");
} }
@ -59,8 +59,8 @@ std::unique_ptr<Result> Result::create(uint64 queryId, const MTPBotInlineResult
auto getInlineResultType = [](const MTPBotInlineResult &inlineResult) -> Type { auto getInlineResultType = [](const MTPBotInlineResult &inlineResult) -> Type {
QString type; QString type;
switch (inlineResult.type()) { switch (inlineResult.type()) {
case mtpc_botInlineResult: type = qs(inlineResult.c_botInlineResult().vtype); break; case mtpc_botInlineResult: type = qs(inlineResult.c_botInlineResult().vtype()); break;
case mtpc_botInlineMediaResult: type = qs(inlineResult.c_botInlineMediaResult().vtype); break; case mtpc_botInlineMediaResult: type = qs(inlineResult.c_botInlineMediaResult().vtype()); break;
} }
return stringToTypeMap->value(type, Type::Unknown); return stringToTypeMap->value(type, Type::Unknown);
}; };
@ -74,40 +74,40 @@ std::unique_ptr<Result> Result::create(uint64 queryId, const MTPBotInlineResult
switch (mtpData.type()) { switch (mtpData.type()) {
case mtpc_botInlineResult: { case mtpc_botInlineResult: {
const auto &r = mtpData.c_botInlineResult(); const auto &r = mtpData.c_botInlineResult();
result->_id = qs(r.vid); result->_id = qs(r.vid());
if (r.has_title()) result->_title = qs(r.vtitle); result->_title = qs(r.vtitle().value_or_empty());
if (r.has_description()) result->_description = qs(r.vdescription); result->_description = qs(r.vdescription().value_or_empty());
if (r.has_url()) result->_url = qs(r.vurl); result->_url = qs(r.vurl().value_or_empty());
if (r.has_thumb()) { if (const auto thumb = r.vthumb()) {
result->_thumb = Images::Create(r.vthumb, result->thumbBox()); result->_thumb = Images::Create(*thumb, result->thumbBox());
} }
if (r.has_content()) { if (const auto content = r.vcontent()) {
result->_content_url = GetContentUrl(r.vcontent); result->_content_url = GetContentUrl(*content);
if (result->_type == Type::Photo) { if (result->_type == Type::Photo) {
result->_photo = Auth().data().photoFromWeb( result->_photo = Auth().data().photoFromWeb(
r.vcontent, *content,
result->_thumb, result->_thumb,
true); true);
} else { } else {
result->_document = Auth().data().documentFromWeb( result->_document = Auth().data().documentFromWeb(
result->adjustAttributes(r.vcontent), result->adjustAttributes(*content),
result->_thumb); result->_thumb);
} }
} }
message = &r.vsend_message; message = &r.vsend_message();
} break; } break;
case mtpc_botInlineMediaResult: { case mtpc_botInlineMediaResult: {
const auto &r = mtpData.c_botInlineMediaResult(); const auto &r = mtpData.c_botInlineMediaResult();
result->_id = qs(r.vid); result->_id = qs(r.vid());
if (r.has_title()) result->_title = qs(r.vtitle); result->_title = qs(r.vtitle().value_or_empty());
if (r.has_description()) result->_description = qs(r.vdescription); result->_description = qs(r.vdescription().value_or_empty());
if (r.has_photo()) { if (const auto photo = r.vphoto()) {
result->_photo = Auth().data().processPhoto(r.vphoto); result->_photo = Auth().data().processPhoto(*photo);
} }
if (r.has_document()) { if (const auto document = r.vdocument()) {
result->_document = Auth().data().processDocument(r.vdocument); result->_document = Auth().data().processDocument(*document);
} }
message = &r.vsend_message; message = &r.vsend_message();
} break; } break;
} }
auto badAttachment = (result->_photo && result->_photo->isNull()) auto badAttachment = (result->_photo && result->_photo->isNull())
@ -134,35 +134,42 @@ std::unique_ptr<Result> Result::create(uint64 queryId, const MTPBotInlineResult
switch (message->type()) { switch (message->type()) {
case mtpc_botInlineMessageMediaAuto: { case mtpc_botInlineMessageMediaAuto: {
auto &r = message->c_botInlineMessageMediaAuto(); const auto &r = message->c_botInlineMessageMediaAuto();
auto entities = r.has_entities() const auto message = qs(r.vmessage());
? TextUtilities::EntitiesFromMTP(r.ventities.v) const auto entities = TextUtilities::EntitiesFromMTP(
: EntitiesInText(); r.ventities().value_or_empty());
if (result->_type == Type::Photo) { if (result->_type == Type::Photo) {
if (!result->_photo) { if (!result->_photo) {
return nullptr; return nullptr;
} }
result->sendData = std::make_unique<internal::SendPhoto>(result->_photo, qs(r.vmessage), entities); result->sendData = std::make_unique<internal::SendPhoto>(
result->_photo,
message,
entities);
} else if (result->_type == Type::Game) { } else if (result->_type == Type::Game) {
result->createGame(); result->createGame();
result->sendData = std::make_unique<internal::SendGame>(result->_game); result->sendData = std::make_unique<internal::SendGame>(
result->_game);
} else { } else {
if (!result->_document) { if (!result->_document) {
return nullptr; return nullptr;
} }
result->sendData = std::make_unique<internal::SendFile>(result->_document, qs(r.vmessage), entities); result->sendData = std::make_unique<internal::SendFile>(
result->_document,
message,
entities);
} }
if (r.has_reply_markup()) { if (const auto markup = r.vreply_markup()) {
result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(r.vreply_markup); result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(*markup);
} }
} break; } break;
case mtpc_botInlineMessageText: { case mtpc_botInlineMessageText: {
auto &r = message->c_botInlineMessageText(); const auto &r = message->c_botInlineMessageText();
auto entities = r.has_entities() result->sendData = std::make_unique<internal::SendText>(
? TextUtilities::EntitiesFromMTP(r.ventities.v) qs(r.vmessage()),
: EntitiesInText(); TextUtilities::EntitiesFromMTP(r.ventities().value_or_empty()),
result->sendData = std::make_unique<internal::SendText>(qs(r.vmessage), entities, r.is_no_webpage()); r.is_no_webpage());
if (result->_type == Type::Photo) { if (result->_type == Type::Photo) {
if (!result->_photo) { if (!result->_photo) {
return nullptr; return nullptr;
@ -176,41 +183,41 @@ std::unique_ptr<Result> Result::create(uint64 queryId, const MTPBotInlineResult
return nullptr; return nullptr;
} }
} }
if (r.has_reply_markup()) { if (const auto markup = r.vreply_markup()) {
result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(r.vreply_markup); result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(*markup);
} }
} break; } break;
case mtpc_botInlineMessageMediaGeo: { case mtpc_botInlineMessageMediaGeo: {
// #TODO layer 72 save period and send live location?.. // #TODO layer 72 save period and send live location?..
auto &r = message->c_botInlineMessageMediaGeo(); auto &r = message->c_botInlineMessageMediaGeo();
if (r.vgeo.type() == mtpc_geoPoint) { if (r.vgeo().type() == mtpc_geoPoint) {
result->sendData = std::make_unique<internal::SendGeo>(r.vgeo.c_geoPoint()); result->sendData = std::make_unique<internal::SendGeo>(r.vgeo().c_geoPoint());
} else { } else {
badAttachment = true; badAttachment = true;
} }
if (r.has_reply_markup()) { if (const auto markup = r.vreply_markup()) {
result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(r.vreply_markup); result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(*markup);
} }
} break; } break;
case mtpc_botInlineMessageMediaVenue: { case mtpc_botInlineMessageMediaVenue: {
auto &r = message->c_botInlineMessageMediaVenue(); auto &r = message->c_botInlineMessageMediaVenue();
if (r.vgeo.type() == mtpc_geoPoint) { if (r.vgeo().type() == mtpc_geoPoint) {
result->sendData = std::make_unique<internal::SendVenue>(r.vgeo.c_geoPoint(), qs(r.vvenue_id), qs(r.vprovider), qs(r.vtitle), qs(r.vaddress)); result->sendData = std::make_unique<internal::SendVenue>(r.vgeo().c_geoPoint(), qs(r.vvenue_id()), qs(r.vprovider()), qs(r.vtitle()), qs(r.vaddress()));
} else { } else {
badAttachment = true; badAttachment = true;
} }
if (r.has_reply_markup()) { if (const auto markup = r.vreply_markup()) {
result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(r.vreply_markup); result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(*markup);
} }
} break; } break;
case mtpc_botInlineMessageMediaContact: { case mtpc_botInlineMessageMediaContact: {
auto &r = message->c_botInlineMessageMediaContact(); auto &r = message->c_botInlineMessageMediaContact();
result->sendData = std::make_unique<internal::SendContact>(qs(r.vfirst_name), qs(r.vlast_name), qs(r.vphone_number)); result->sendData = std::make_unique<internal::SendContact>(qs(r.vfirst_name()), qs(r.vlast_name()), qs(r.vphone_number()));
if (r.has_reply_markup()) { if (const auto markup = r.vreply_markup()) {
result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(r.vreply_markup); result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(*markup);
} }
} break; } break;
@ -367,20 +374,20 @@ MTPWebDocument Result::adjustAttributes(const MTPWebDocument &document) {
case mtpc_webDocument: { case mtpc_webDocument: {
const auto &data = document.c_webDocument(); const auto &data = document.c_webDocument();
return MTP_webDocument( return MTP_webDocument(
data.vurl, data.vurl(),
data.vaccess_hash, data.vaccess_hash(),
data.vsize, data.vsize(),
data.vmime_type, data.vmime_type(),
adjustAttributes(data.vattributes, data.vmime_type)); adjustAttributes(data.vattributes(), data.vmime_type()));
} break; } break;
case mtpc_webDocumentNoProxy: { case mtpc_webDocumentNoProxy: {
const auto &data = document.c_webDocumentNoProxy(); const auto &data = document.c_webDocumentNoProxy();
return MTP_webDocumentNoProxy( return MTP_webDocumentNoProxy(
data.vurl, data.vurl(),
data.vsize, data.vsize(),
data.vmime_type, data.vmime_type(),
adjustAttributes(data.vattributes, data.vmime_type)); adjustAttributes(data.vattributes(), data.vmime_type()));
} break; } break;
} }
Unexpected("Type in InlineBots::Result::adjustAttributes."); Unexpected("Type in InlineBots::Result::adjustAttributes.");
@ -419,19 +426,19 @@ MTPVector<MTPDocumentAttribute> Result::adjustAttributes(
// We always treat audio/ogg as a voice message. // We always treat audio/ogg as a voice message.
// It was that way before we started to get attributes here. // It was that way before we started to get attributes here.
const auto &fields = audio->c_documentAttributeAudio(); const auto &fields = audio->c_documentAttributeAudio();
if (!(fields.vflags.v & Flag::f_voice)) { if (!(fields.vflags().v & Flag::f_voice)) {
*audio = MTP_documentAttributeAudio( *audio = MTP_documentAttributeAudio(
MTP_flags(fields.vflags.v | Flag::f_voice), MTP_flags(fields.vflags().v | Flag::f_voice),
fields.vduration, fields.vduration(),
fields.vtitle, MTP_bytes(fields.vtitle().value_or_empty()),
fields.vperformer, MTP_bytes(fields.vperformer().value_or_empty()),
fields.vwaveform); MTP_bytes(fields.vwaveform().value_or_empty()));
} }
} }
const auto &fields = audio->c_documentAttributeAudio(); const auto &fields = audio->c_documentAttributeAudio();
if (!exists(mtpc_documentAttributeFilename) if (!exists(mtpc_documentAttributeFilename)
&& !(fields.vflags.v & Flag::f_voice)) { && !(fields.vflags().v & Flag::f_voice)) {
const auto p = Core::MimeTypeForName(mime).globPatterns(); const auto p = Core::MimeTypeForName(mime).globPatterns();
auto pattern = p.isEmpty() ? QString() : p.front(); auto pattern = p.isEmpty() ? QString() : p.front();
const auto extension = pattern.isEmpty() const auto extension = pattern.isEmpty()

View file

@ -59,8 +59,8 @@ public:
class SendDataCommon : public SendData { class SendDataCommon : public SendData {
public: public:
struct SentMTPMessageFields { struct SentMTPMessageFields {
MTPString text = MTP_string(""); MTPString text = MTP_string();
MTPVector<MTPMessageEntity> entities = MTPnullEntities; MTPVector<MTPMessageEntity> entities = MTP_vector<MTPMessageEntity>();
MTPMessageMedia media = MTP_messageMediaEmpty(); MTPMessageMedia media = MTP_messageMediaEmpty();
}; };
virtual SentMTPMessageFields getSentMessageFields() const = 0; virtual SentMTPMessageFields getSentMessageFields() const = 0;

View file

@ -1045,20 +1045,21 @@ void Widget::inlineResultsDone(const MTPmessages_BotResults &result) {
auto adding = (it != _inlineCache.cend()); auto adding = (it != _inlineCache.cend());
if (result.type() == mtpc_messages_botResults) { if (result.type() == mtpc_messages_botResults) {
auto &d = result.c_messages_botResults(); auto &d = result.c_messages_botResults();
Auth().data().processUsers(d.vusers); Auth().data().processUsers(d.vusers());
auto &v = d.vresults.v; auto &v = d.vresults().v;
auto queryId = d.vquery_id.v; auto queryId = d.vquery_id().v;
if (it == _inlineCache.cend()) { if (it == _inlineCache.cend()) {
it = _inlineCache.emplace(_inlineQuery, std::make_unique<internal::CacheEntry>()).first; it = _inlineCache.emplace(_inlineQuery, std::make_unique<internal::CacheEntry>()).first;
} }
auto entry = it->second.get(); auto entry = it->second.get();
entry->nextOffset = qs(d.vnext_offset); entry->nextOffset = qs(d.vnext_offset().value_or_empty());
if (d.has_switch_pm() && d.vswitch_pm.type() == mtpc_inlineBotSwitchPM) { if (const auto switchPm = d.vswitch_pm()) {
auto &switchPm = d.vswitch_pm.c_inlineBotSwitchPM(); switchPm->match([&](const MTPDinlineBotSwitchPM &data) {
entry->switchPmText = qs(switchPm.vtext); entry->switchPmText = qs(data.vtext());
entry->switchPmStartToken = qs(switchPm.vstart_param); entry->switchPmStartToken = qs(data.vstart_param());
});
} }
if (auto count = v.size()) { if (auto count = v.size()) {

View file

@ -229,12 +229,12 @@ void CodeWidget::codeSubmitDone(const MTPauth_Authorization &result) {
stopCheck(); stopCheck();
_sentRequest = 0; _sentRequest = 0;
auto &d = result.c_auth_authorization(); auto &d = result.c_auth_authorization();
if (d.vuser.type() != mtpc_user || !d.vuser.c_user().is_self()) { // wtf? if (d.vuser().type() != mtpc_user || !d.vuser().c_user().is_self()) { // wtf?
showCodeError(rpl::single(Lang::Hard::ServerError())); showCodeError(rpl::single(Lang::Hard::ServerError()));
return; return;
} }
cSetLoggedPhoneNumber(getData()->phone); cSetLoggedPhoneNumber(getData()->phone);
finish(d.vuser); finish(d.vuser());
} }
bool CodeWidget::codeSubmitFail(const RPCError &error) { bool CodeWidget::codeSubmitFail(const RPCError &error) {
@ -314,7 +314,7 @@ void CodeWidget::gotPassword(const MTPaccount_Password &result) {
_sentRequest = 0; _sentRequest = 0;
const auto &d = result.c_account_password(); const auto &d = result.c_account_password();
getData()->pwdRequest = Core::ParseCloudPasswordCheckRequest(d); getData()->pwdRequest = Core::ParseCloudPasswordCheckRequest(d);
if (!d.has_current_algo() || !d.has_srp_id() || !d.has_srp_B()) { if (!d.vcurrent_algo() || !d.vsrp_id() || !d.vsrp_B()) {
LOG(("API Error: No current password received on login.")); LOG(("API Error: No current password received on login."));
_code->setFocus(); _code->setFocus();
return; return;
@ -331,7 +331,7 @@ void CodeWidget::gotPassword(const MTPaccount_Password &result) {
return; return;
} }
getData()->hasRecovery = d.is_has_recovery(); getData()->hasRecovery = d.is_has_recovery();
getData()->pwdHint = qs(d.vhint); getData()->pwdHint = qs(d.vhint().value_or_empty());
getData()->pwdNotEmptyPassport = d.is_has_secure_values(); getData()->pwdNotEmptyPassport = d.is_has_secure_values();
goReplace(new Intro::PwdCheckWidget(parentWidget(), getData())); goReplace(new Intro::PwdCheckWidget(parentWidget(), getData()));
} }
@ -377,9 +377,10 @@ void CodeWidget::noTelegramCodeDone(const MTPauth_SentCode &result) {
const auto &d = result.c_auth_sentCode(); const auto &d = result.c_auth_sentCode();
fillSentCodeData(d); fillSentCodeData(d);
_code->setDigitsCountMax(getData()->codeLength); _code->setDigitsCountMax(getData()->codeLength);
if (d.has_next_type() && d.vnext_type.type() == mtpc_auth_codeTypeCall) { const auto next = d.vnext_type();
if (next && next->type() == mtpc_auth_codeTypeCall) {
getData()->callStatus = Widget::Data::CallStatus::Waiting; getData()->callStatus = Widget::Data::CallStatus::Waiting;
getData()->callTimeout = d.has_timeout() ? d.vtimeout.v : 60; getData()->callTimeout = d.vtimeout().value_or(60);
} else { } else {
getData()->callStatus = Widget::Data::CallStatus::Disabled; getData()->callStatus = Widget::Data::CallStatus::Disabled;
getData()->callTimeout = 0; getData()->callTimeout = 0;

View file

@ -153,11 +153,12 @@ void PhoneWidget::phoneSubmitDone(const MTPauth_SentCode &result) {
const auto &d = result.c_auth_sentCode(); const auto &d = result.c_auth_sentCode();
fillSentCodeData(d); fillSentCodeData(d);
getData()->phone = _sentPhone; getData()->phone = _sentPhone;
getData()->phoneHash = qba(d.vphone_code_hash); getData()->phoneHash = qba(d.vphone_code_hash());
getData()->phoneIsRegistered = d.is_phone_registered(); getData()->phoneIsRegistered = d.is_phone_registered();
if (d.has_next_type() && d.vnext_type.type() == mtpc_auth_codeTypeCall) { const auto next = d.vnext_type();
if (next && next->type() == mtpc_auth_codeTypeCall) {
getData()->callStatus = Widget::Data::CallStatus::Waiting; getData()->callStatus = Widget::Data::CallStatus::Waiting;
getData()->callTimeout = d.has_timeout() ? d.vtimeout.v : 60; getData()->callTimeout = d.vtimeout().value_or(60);
} else { } else {
getData()->callStatus = Widget::Data::CallStatus::Disabled; getData()->callStatus = Widget::Data::CallStatus::Disabled;
getData()->callTimeout = 0; getData()->callTimeout = 0;

View file

@ -136,11 +136,11 @@ void PwdCheckWidget::pwdSubmitDone(bool recover, const MTPauth_Authorization &re
cSetPasswordRecovered(true); cSetPasswordRecovered(true);
} }
auto &d = result.c_auth_authorization(); auto &d = result.c_auth_authorization();
if (d.vuser.type() != mtpc_user || !d.vuser.c_user().is_self()) { // wtf? if (d.vuser().type() != mtpc_user || !d.vuser().c_user().is_self()) { // wtf?
showError(rpl::single(Lang::Hard::ServerError())); showError(rpl::single(Lang::Hard::ServerError()));
return; return;
} }
finish(d.vuser); finish(d.vuser());
} }
void PwdCheckWidget::pwdSubmitFail(const RPCError &error) { void PwdCheckWidget::pwdSubmitFail(const RPCError &error) {
@ -265,7 +265,7 @@ void PwdCheckWidget::codeSubmitFail(const RPCError &error) {
} }
void PwdCheckWidget::recoverStarted(const MTPauth_PasswordRecovery &result) { void PwdCheckWidget::recoverStarted(const MTPauth_PasswordRecovery &result) {
_emailPattern = qs(result.c_auth_passwordRecovery().vemail_pattern); _emailPattern = qs(result.c_auth_passwordRecovery().vemail_pattern());
updateDescriptionText(); updateDescriptionText();
} }

View file

@ -121,11 +121,11 @@ void SignupWidget::onCheckRequest() {
void SignupWidget::nameSubmitDone(const MTPauth_Authorization &result) { void SignupWidget::nameSubmitDone(const MTPauth_Authorization &result) {
stopCheck(); stopCheck();
auto &d = result.c_auth_authorization(); auto &d = result.c_auth_authorization();
if (d.vuser.type() != mtpc_user || !d.vuser.c_user().is_self()) { // wtf? if (d.vuser().type() != mtpc_user || !d.vuser().c_user().is_self()) { // wtf?
showError(rpl::single(Lang::Hard::ServerError())); showError(rpl::single(Lang::Hard::ServerError()));
return; return;
} }
finish(d.vuser, _photo->takeResultImage()); finish(d.vuser(), _photo->takeResultImage());
} }
bool SignupWidget::nameSubmitFail(const RPCError &error) { bool SignupWidget::nameSubmitFail(const RPCError &error) {

View file

@ -431,11 +431,11 @@ void Widget::getNearestDC() {
request(MTPhelp_GetNearestDc()).done([this](const MTPNearestDc &result) { request(MTPhelp_GetNearestDc()).done([this](const MTPNearestDc &result) {
auto &nearest = result.c_nearestDc(); auto &nearest = result.c_nearestDc();
DEBUG_LOG(("Got nearest dc, country: %1, nearest: %2, this: %3" DEBUG_LOG(("Got nearest dc, country: %1, nearest: %2, this: %3"
).arg(qs(nearest.vcountry) ).arg(qs(nearest.vcountry())
).arg(nearest.vnearest_dc.v ).arg(nearest.vnearest_dc().v
).arg(nearest.vthis_dc.v)); ).arg(nearest.vthis_dc().v));
Core::App().suggestMainDcId(nearest.vnearest_dc.v); Core::App().suggestMainDcId(nearest.vnearest_dc().v);
auto nearestCountry = qs(nearest.vcountry); auto nearestCountry = qs(nearest.vcountry());
if (getData()->country != nearestCountry) { if (getData()->country != nearestCountry) {
getData()->country = nearestCountry; getData()->country = nearestCountry;
getData()->updated.notify(); getData()->updated.notify();
@ -648,7 +648,7 @@ rpl::producer<QString> Widget::Step::nextButtonText() const {
void Widget::Step::finish(const MTPUser &user, QImage &&photo) { void Widget::Step::finish(const MTPUser &user, QImage &&photo) {
if (user.type() != mtpc_user if (user.type() != mtpc_user
|| !user.c_user().is_self() || !user.c_user().is_self()
|| !user.c_user().vid.v) { || !user.c_user().vid().v) {
// No idea what to do here. // No idea what to do here.
// We could've reset intro and MTP, but this really should not happen. // We could've reset intro and MTP, but this really should not happen.
Ui::show(Box<InformBox>("Internal error: bad user.is_self() after sign in.")); Ui::show(Box<InformBox>("Internal error: bad user.is_self() after sign in."));
@ -776,26 +776,27 @@ bool Widget::Step::paintAnimated(Painter &p, QRect clip) {
} }
void Widget::Step::fillSentCodeData(const MTPDauth_sentCode &data) { void Widget::Step::fillSentCodeData(const MTPDauth_sentCode &data) {
if (data.has_terms_of_service()) { if (const auto terms = data.vterms_of_service()) {
const auto &terms = data.vterms_of_service.c_help_termsOfService(); terms->match([&](const MTPDhelp_termsOfService &data) {
getData()->termsLock = Window::TermsLock::FromMTP(terms); getData()->termsLock = Window::TermsLock::FromMTP(data);
});
} else { } else {
getData()->termsLock = Window::TermsLock(); getData()->termsLock = Window::TermsLock();
} }
const auto &type = data.vtype; const auto &type = data.vtype();
switch (type.type()) { switch (type.type()) {
case mtpc_auth_sentCodeTypeApp: { case mtpc_auth_sentCodeTypeApp: {
getData()->codeByTelegram = true; getData()->codeByTelegram = true;
getData()->codeLength = type.c_auth_sentCodeTypeApp().vlength.v; getData()->codeLength = type.c_auth_sentCodeTypeApp().vlength().v;
} break; } break;
case mtpc_auth_sentCodeTypeSms: { case mtpc_auth_sentCodeTypeSms: {
getData()->codeByTelegram = false; getData()->codeByTelegram = false;
getData()->codeLength = type.c_auth_sentCodeTypeSms().vlength.v; getData()->codeLength = type.c_auth_sentCodeTypeSms().vlength().v;
} break; } break;
case mtpc_auth_sentCodeTypeCall: { case mtpc_auth_sentCodeTypeCall: {
getData()->codeByTelegram = false; getData()->codeByTelegram = false;
getData()->codeLength = type.c_auth_sentCodeTypeCall().vlength.v; getData()->codeLength = type.c_auth_sentCodeTypeCall().vlength().v;
} break; } break;
case mtpc_auth_sentCodeTypeFlashCall: LOG(("Error: should not be flashcall!")); break; case mtpc_auth_sentCodeTypeFlashCall: LOG(("Error: should not be flashcall!")); break;
} }

View file

@ -63,10 +63,10 @@ ConfirmSwitchBox::ConfirmSwitchBox(
QWidget*, QWidget*,
const MTPDlangPackLanguage &data, const MTPDlangPackLanguage &data,
Fn<void()> apply) Fn<void()> apply)
: _name(qs(data.vnative_name)) : _name(qs(data.vnative_name()))
, _percent(data.vtranslated_count.v * 100 / data.vstrings_count.v) , _percent(data.vtranslated_count().v * 100 / data.vstrings_count().v)
, _official(data.is_official()) , _official(data.is_official())
, _editLink(qs(data.vtranslations_url)) , _editLink(qs(data.vtranslations_url()))
, _apply(std::move(apply)) { , _apply(std::move(apply)) {
} }
@ -109,8 +109,8 @@ void ConfirmSwitchBox::prepare() {
NotReadyBox::NotReadyBox( NotReadyBox::NotReadyBox(
QWidget*, QWidget*,
const MTPDlangPackLanguage &data) const MTPDlangPackLanguage &data)
: _name(qs(data.vnative_name)) : _name(qs(data.vnative_name()))
, _editLink(qs(data.vtranslations_url)) { , _editLink(qs(data.vtranslations_url())) {
} }
void NotReadyBox::prepare() { void NotReadyBox::prepare() {
@ -145,13 +145,11 @@ void NotReadyBox::prepare() {
Language ParseLanguage(const MTPLangPackLanguage &data) { Language ParseLanguage(const MTPLangPackLanguage &data) {
return data.match([](const MTPDlangPackLanguage &data) { return data.match([](const MTPDlangPackLanguage &data) {
return Language{ return Language{
qs(data.vlang_code), qs(data.vlang_code()),
qs(data.vplural_code), qs(data.vplural_code()),
(data.has_base_lang_code() qs(data.vbase_lang_code().value_or_empty()),
? qs(data.vbase_lang_code) qs(data.vname()),
: QString()), qs(data.vnative_name())
qs(data.vname),
qs(data.vnative_name)
}; };
}); });
} }
@ -268,7 +266,7 @@ void CloudManager::applyLangPackDifference(
} }
const auto &langpack = difference.c_langPackDifference(); const auto &langpack = difference.c_langPackDifference();
const auto langpackId = qs(langpack.vlang_code); const auto langpackId = qs(langpack.vlang_code());
const auto pack = packTypeFromId(langpackId); const auto pack = packTypeFromId(langpackId);
if (pack != Pack::None) { if (pack != Pack::None) {
applyLangPackData(pack, langpack); applyLangPackData(pack, langpack);
@ -356,9 +354,9 @@ bool CloudManager::showOfferSwitchBox() {
void CloudManager::applyLangPackData( void CloudManager::applyLangPackData(
Pack pack, Pack pack,
const MTPDlangPackDifference &data) { const MTPDlangPackDifference &data) {
if (_langpack.version(pack) < data.vfrom_version.v) { if (_langpack.version(pack) < data.vfrom_version().v) {
requestLangPackDifference(pack); requestLangPackDifference(pack);
} else if (!data.vstrings.v.isEmpty()) { } else if (!data.vstrings().v.isEmpty()) {
_langpack.applyDifference(pack, data); _langpack.applyDifference(pack, data);
Local::writeLangPack(); Local::writeLangPack();
} else if (_restartAfterSwitch) { } else if (_restartAfterSwitch) {
@ -421,7 +419,7 @@ void CloudManager::requestLanguageAndSwitch(
return; return;
} }
result.match([=](const MTPDlangPackLanguage &data) { result.match([=](const MTPDlangPackLanguage &data) {
if (data.vstrings_count.v > 0) { if (data.vstrings_count().v > 0) {
Ui::show(Box<ConfirmSwitchBox>(data, finalize)); Ui::show(Box<ConfirmSwitchBox>(data, finalize));
} else { } else {
Ui::show(Box<NotReadyBox>(data)); Ui::show(Box<NotReadyBox>(data));

View file

@ -611,27 +611,17 @@ void HandleString(
SetCallback setCallback, SetCallback setCallback,
ResetCallback resetCallback) { ResetCallback resetCallback) {
string.match([&](const MTPDlangPackString &data) { string.match([&](const MTPDlangPackString &data) {
setCallback(qba(data.vkey), qba(data.vvalue)); setCallback(qba(data.vkey()), qba(data.vvalue()));
}, [&](const MTPDlangPackStringPluralized &data) { }, [&](const MTPDlangPackStringPluralized &data) {
const auto key = qba(data.vkey); const auto key = qba(data.vkey());
setCallback( setCallback(key + "#zero", data.vzero_value().value_or_empty());
key + "#zero", setCallback(key + "#one", data.vone_value().value_or_empty());
data.has_zero_value() ? qba(data.vzero_value) : QByteArray()); setCallback(key + "#two", data.vtwo_value().value_or_empty());
setCallback( setCallback(key + "#few", data.vfew_value().value_or_empty());
key + "#one", setCallback(key + "#many", data.vmany_value().value_or_empty());
data.has_one_value() ? qba(data.vone_value) : QByteArray()); setCallback(key + "#other", qba(data.vother_value()));
setCallback(
key + "#two",
data.has_two_value() ? qba(data.vtwo_value) : QByteArray());
setCallback(
key + "#few",
data.has_few_value() ? qba(data.vfew_value) : QByteArray());
setCallback(
key + "#many",
data.has_many_value() ? qba(data.vmany_value) : QByteArray());
setCallback(key + "#other", qba(data.vother_value));
}, [&](const MTPDlangPackStringDeleted &data) { }, [&](const MTPDlangPackStringDeleted &data) {
auto key = qba(data.vkey); auto key = qba(data.vkey());
resetCallback(key); resetCallback(key);
const auto postfixes = { const auto postfixes = {
"#zero", "#zero",
@ -665,11 +655,11 @@ void Instance::applyDifference(
void Instance::applyDifferenceToMe( void Instance::applyDifferenceToMe(
const MTPDlangPackDifference &difference) { const MTPDlangPackDifference &difference) {
Expects(LanguageIdOrDefault(_id) == qs(difference.vlang_code)); Expects(LanguageIdOrDefault(_id) == qs(difference.vlang_code()));
Expects(difference.vfrom_version.v <= _version); Expects(difference.vfrom_version().v <= _version);
_version = difference.vversion.v; _version = difference.vversion().v;
for (const auto &string : difference.vstrings.v) { for (const auto &string : difference.vstrings().v) {
HandleString(string, [&](auto &&key, auto &&value) { HandleString(string, [&](auto &&key, auto &&value) {
applyValue(key, value); applyValue(key, value);
}, [&](auto &&key) { }, [&](auto &&key) {

File diff suppressed because it is too large Load diff

View file

@ -144,15 +144,15 @@ void LoaderMtproto::requestDone(int offset, const MTPupload_File &result) {
result.match([&](const MTPDupload_file &data) { result.match([&](const MTPDupload_file &data) {
_requests.erase(offset); _requests.erase(offset);
sendNext(); sendNext();
_parts.fire({ offset, data.vbytes.v }); _parts.fire({ offset, data.vbytes().v });
}, [&](const MTPDupload_fileCdnRedirect &data) { }, [&](const MTPDupload_fileCdnRedirect &data) {
changeCdnParams( changeCdnParams(
offset, offset,
data.vdc_id.v, data.vdc_id().v,
data.vfile_token.v, data.vfile_token().v,
data.vencryption_key.v, data.vencryption_key().v,
data.vencryption_iv.v, data.vencryption_iv().v,
data.vfile_hashes.v); data.vfile_hashes().v);
}); });
} }

View file

@ -199,14 +199,14 @@ void ConfigLoader::specialConfigLoaded(const MTPConfig &result) {
Expects(result.type() == mtpc_config); Expects(result.type() == mtpc_config);
auto &data = result.c_config(); auto &data = result.c_config();
if (data.vdc_options.v.empty()) { if (data.vdc_options().v.empty()) {
LOG(("MTP Error: config with empty dc_options received!")); LOG(("MTP Error: config with empty dc_options received!"));
return; return;
} }
// We use special config only for dc options. // We use special config only for dc options.
// For everything else we wait for normal config from main dc. // For everything else we wait for normal config from main dc.
_instance->dcOptions()->setFromList(data.vdc_options); _instance->dcOptions()->setFromList(data.vdc_options());
} }
} // namespace internal } // namespace internal

View file

@ -1681,7 +1681,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
case mtpc_msgs_ack: { case mtpc_msgs_ack: {
MTPMsgsAck msg; MTPMsgsAck msg;
msg.read(from, end); msg.read(from, end);
auto &ids = msg.c_msgs_ack().vmsg_ids.v; auto &ids = msg.c_msgs_ack().vmsg_ids().v;
uint32 idsCount = ids.size(); uint32 idsCount = ids.size();
DEBUG_LOG(("Message Info: acks received, ids: %1").arg(LogIdsVector(ids))); DEBUG_LOG(("Message Info: acks received, ids: %1").arg(LogIdsVector(ids)));
@ -1701,13 +1701,13 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
MTPBadMsgNotification msg; MTPBadMsgNotification msg;
msg.read(from, end); msg.read(from, end);
const auto &data(msg.c_bad_msg_notification()); const auto &data(msg.c_bad_msg_notification());
LOG(("Message Info: bad message notification received (error_code %3) for msg_id = %1, seq_no = %2").arg(data.vbad_msg_id.v).arg(data.vbad_msg_seqno.v).arg(data.verror_code.v)); LOG(("Message Info: bad message notification received (error_code %3) for msg_id = %1, seq_no = %2").arg(data.vbad_msg_id().v).arg(data.vbad_msg_seqno().v).arg(data.verror_code().v));
mtpMsgId resendId = data.vbad_msg_id.v; mtpMsgId resendId = data.vbad_msg_id().v;
if (resendId == _pingMsgId) { if (resendId == _pingMsgId) {
_pingId = 0; _pingId = 0;
} }
int32 errorCode = data.verror_code.v; int32 errorCode = data.verror_code().v;
if (false if (false
|| errorCode == 16 || errorCode == 16
|| errorCode == 17 || errorCode == 17
@ -1768,11 +1768,11 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
unixtimeSet(serverTime, true); unixtimeSet(serverTime, true);
badTime = false; badTime = false;
} }
LOG(("Message Info: bad message notification received, msgId %1, error_code %2").arg(data.vbad_msg_id.v).arg(errorCode)); LOG(("Message Info: bad message notification received, msgId %1, error_code %2").arg(data.vbad_msg_id().v).arg(errorCode));
return HandleResult::ResetSession; return HandleResult::ResetSession;
} }
} else { // fatal (except 48, but it must not get here) } else { // fatal (except 48, but it must not get here)
const auto badMsgId = mtpMsgId(data.vbad_msg_id.v); const auto badMsgId = mtpMsgId(data.vbad_msg_id().v);
const auto requestId = wasSent(resendId); const auto requestId = wasSent(resendId);
if (requestId) { if (requestId) {
LOG(("Message Error: " LOG(("Message Error: "
@ -1798,9 +1798,9 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
MTPBadMsgNotification msg; MTPBadMsgNotification msg;
msg.read(from, end); msg.read(from, end);
const auto &data(msg.c_bad_server_salt()); const auto &data(msg.c_bad_server_salt());
DEBUG_LOG(("Message Info: bad server salt received (error_code %4) for msg_id = %1, seq_no = %2, new salt: %3").arg(data.vbad_msg_id.v).arg(data.vbad_msg_seqno.v).arg(data.vnew_server_salt.v).arg(data.verror_code.v)); DEBUG_LOG(("Message Info: bad server salt received (error_code %4) for msg_id = %1, seq_no = %2, new salt: %3").arg(data.vbad_msg_id().v).arg(data.vbad_msg_seqno().v).arg(data.vnew_server_salt().v).arg(data.verror_code().v));
mtpMsgId resendId = data.vbad_msg_id.v; mtpMsgId resendId = data.vbad_msg_id().v;
if (resendId == _pingMsgId) { if (resendId == _pingMsgId) {
_pingId = 0; _pingId = 0;
} else if (!wasSent(resendId)) { } else if (!wasSent(resendId)) {
@ -1808,7 +1808,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
return (badTime ? HandleResult::Ignored : HandleResult::Success); return (badTime ? HandleResult::Ignored : HandleResult::Success);
} }
uint64 serverSalt = data.vnew_server_salt.v; uint64 serverSalt = data.vnew_server_salt().v;
sessionData->setSalt(serverSalt); sessionData->setSalt(serverSalt);
unixtimeSet(serverTime); unixtimeSet(serverTime);
@ -1832,7 +1832,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
} }
MTPMsgsStateReq msg; MTPMsgsStateReq msg;
msg.read(from, end); msg.read(from, end);
auto &ids = msg.c_msgs_state_req().vmsg_ids.v; auto &ids = msg.c_msgs_state_req().vmsg_ids().v;
auto idsCount = ids.size(); auto idsCount = ids.size();
DEBUG_LOG(("Message Info: msgs_state_req received, ids: %1").arg(LogIdsVector(ids))); DEBUG_LOG(("Message Info: msgs_state_req received, ids: %1").arg(LogIdsVector(ids)));
if (!idsCount) return HandleResult::Success; if (!idsCount) return HandleResult::Success;
@ -1882,8 +1882,8 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
msg.read(from, end); msg.read(from, end);
auto &data = msg.c_msgs_state_info(); auto &data = msg.c_msgs_state_info();
auto reqMsgId = data.vreq_msg_id.v; auto reqMsgId = data.vreq_msg_id().v;
auto &states = data.vinfo.v; auto &states = data.vinfo().v;
DEBUG_LOG(("Message Info: msg state received, msgId %1, reqMsgId: %2, HEX states %3").arg(msgId).arg(reqMsgId).arg(Logs::mb(states.data(), states.length()).str())); DEBUG_LOG(("Message Info: msg state received, msgId %1, reqMsgId: %2, HEX states %3").arg(msgId).arg(reqMsgId).arg(Logs::mb(states.data(), states.length()).str()));
SecureRequest requestBuffer; SecureRequest requestBuffer;
@ -1917,11 +1917,11 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
if (mtpTypeId(*rFrom) == mtpc_msgs_state_req) { if (mtpTypeId(*rFrom) == mtpc_msgs_state_req) {
MTPMsgsStateReq request; MTPMsgsStateReq request;
request.read(rFrom, rEnd); request.read(rFrom, rEnd);
handleMsgsStates(request.c_msgs_state_req().vmsg_ids.v, states, toAck); handleMsgsStates(request.c_msgs_state_req().vmsg_ids().v, states, toAck);
} else { } else {
MTPMsgResendReq request; MTPMsgResendReq request;
request.read(rFrom, rEnd); request.read(rFrom, rEnd);
handleMsgsStates(request.c_msg_resend_req().vmsg_ids.v, states, toAck); handleMsgsStates(request.c_msg_resend_req().vmsg_ids().v, states, toAck);
} }
} catch(Exception &) { } catch(Exception &) {
LOG(("Message Error: could not parse sent msgs_state_req")); LOG(("Message Error: could not parse sent msgs_state_req"));
@ -1940,8 +1940,8 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
MTPMsgsAllInfo msg; MTPMsgsAllInfo msg;
msg.read(from, end); msg.read(from, end);
auto &data = msg.c_msgs_all_info(); auto &data = msg.c_msgs_all_info();
auto &ids = data.vmsg_ids.v; auto &ids = data.vmsg_ids().v;
auto &states = data.vinfo.v; auto &states = data.vinfo().v;
QVector<MTPlong> toAck; QVector<MTPlong> toAck;
@ -1956,21 +1956,21 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
msg.read(from, end); msg.read(from, end);
const auto &data(msg.c_msg_detailed_info()); const auto &data(msg.c_msg_detailed_info());
DEBUG_LOG(("Message Info: msg detailed info, sent msgId %1, answerId %2, status %3, bytes %4").arg(data.vmsg_id.v).arg(data.vanswer_msg_id.v).arg(data.vstatus.v).arg(data.vbytes.v)); DEBUG_LOG(("Message Info: msg detailed info, sent msgId %1, answerId %2, status %3, bytes %4").arg(data.vmsg_id().v).arg(data.vanswer_msg_id().v).arg(data.vstatus().v).arg(data.vbytes().v));
QVector<MTPlong> ids(1, data.vmsg_id); QVector<MTPlong> ids(1, data.vmsg_id());
if (badTime) { if (badTime) {
if (requestsFixTimeSalt(ids, serverTime, serverSalt)) { if (requestsFixTimeSalt(ids, serverTime, serverSalt)) {
badTime = false; badTime = false;
} else { } else {
DEBUG_LOG(("Message Info: error, such message was not sent recently %1").arg(data.vmsg_id.v)); DEBUG_LOG(("Message Info: error, such message was not sent recently %1").arg(data.vmsg_id().v));
return HandleResult::Ignored; return HandleResult::Ignored;
} }
} }
requestsAcked(ids); requestsAcked(ids);
bool received = false; bool received = false;
MTPlong resMsgId = data.vanswer_msg_id; MTPlong resMsgId = data.vanswer_msg_id();
{ {
QReadLocker lock(sessionData->receivedIdsMutex()); QReadLocker lock(sessionData->receivedIdsMutex());
received = (sessionData->receivedIdsSet().lookup(resMsgId.v) != ReceivedMsgIds::State::NotFound); received = (sessionData->receivedIdsSet().lookup(resMsgId.v) != ReceivedMsgIds::State::NotFound);
@ -1992,10 +1992,10 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
msg.read(from, end); msg.read(from, end);
const auto &data(msg.c_msg_new_detailed_info()); const auto &data(msg.c_msg_new_detailed_info());
DEBUG_LOG(("Message Info: msg new detailed info, answerId %2, status %3, bytes %4").arg(data.vanswer_msg_id.v).arg(data.vstatus.v).arg(data.vbytes.v)); DEBUG_LOG(("Message Info: msg new detailed info, answerId %2, status %3, bytes %4").arg(data.vanswer_msg_id().v).arg(data.vstatus().v).arg(data.vbytes().v));
bool received = false; bool received = false;
MTPlong resMsgId = data.vanswer_msg_id; MTPlong resMsgId = data.vanswer_msg_id();
{ {
QReadLocker lock(sessionData->receivedIdsMutex()); QReadLocker lock(sessionData->receivedIdsMutex());
received = (sessionData->receivedIdsSet().lookup(resMsgId.v) != ReceivedMsgIds::State::NotFound); received = (sessionData->receivedIdsSet().lookup(resMsgId.v) != ReceivedMsgIds::State::NotFound);
@ -2011,7 +2011,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
case mtpc_msg_resend_req: { case mtpc_msg_resend_req: {
MTPMsgResendReq msg; MTPMsgResendReq msg;
msg.read(from, end); msg.read(from, end);
auto &ids = msg.c_msg_resend_req().vmsg_ids.v; auto &ids = msg.c_msg_resend_req().vmsg_ids().v;
auto idsCount = ids.size(); auto idsCount = ids.size();
DEBUG_LOG(("Message Info: resend of msgs requested, ids: %1").arg(LogIdsVector(ids))); DEBUG_LOG(("Message Info: resend of msgs requested, ids: %1").arg(LogIdsVector(ids)));
@ -2083,18 +2083,18 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
const auto &data(msg.c_new_session_created()); const auto &data(msg.c_new_session_created());
if (badTime) { if (badTime) {
if (requestsFixTimeSalt(QVector<MTPlong>(1, data.vfirst_msg_id), serverTime, serverSalt)) { if (requestsFixTimeSalt(QVector<MTPlong>(1, data.vfirst_msg_id()), serverTime, serverSalt)) {
badTime = false; badTime = false;
} else { } else {
DEBUG_LOG(("Message Info: error, such message was not sent recently %1").arg(data.vfirst_msg_id.v)); DEBUG_LOG(("Message Info: error, such message was not sent recently %1").arg(data.vfirst_msg_id().v));
return HandleResult::Ignored; return HandleResult::Ignored;
} }
} }
DEBUG_LOG(("Message Info: new server session created, unique_id %1, first_msg_id %2, server_salt %3").arg(data.vunique_id.v).arg(data.vfirst_msg_id.v).arg(data.vserver_salt.v)); DEBUG_LOG(("Message Info: new server session created, unique_id %1, first_msg_id %2, server_salt %3").arg(data.vunique_id().v).arg(data.vfirst_msg_id().v).arg(data.vserver_salt().v));
sessionData->setSalt(data.vserver_salt.v); sessionData->setSalt(data.vserver_salt().v);
mtpMsgId firstMsgId = data.vfirst_msg_id.v; mtpMsgId firstMsgId = data.vfirst_msg_id().v;
QVector<quint64> toResend; QVector<quint64> toResend;
{ {
QReadLocker locker(sessionData->haveSentMutex()); QReadLocker locker(sessionData->haveSentMutex());
@ -2115,33 +2115,23 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
sessionData->haveReceivedUpdates().push_back(SerializedMessage(update)); sessionData->haveReceivedUpdates().push_back(SerializedMessage(update));
} return HandleResult::Success; } return HandleResult::Success;
case mtpc_ping: {
if (badTime) return HandleResult::Ignored;
MTPPing msg;
msg.read(from, end);
DEBUG_LOG(("Message Info: ping received, ping_id: %1, sending pong...").arg(msg.vping_id.v));
emit sendPongAsync(msgId, msg.vping_id.v);
} return HandleResult::Success;
case mtpc_pong: { case mtpc_pong: {
MTPPong msg; MTPPong msg;
msg.read(from, end); msg.read(from, end);
const auto &data(msg.c_pong()); const auto &data(msg.c_pong());
DEBUG_LOG(("Message Info: pong received, msg_id: %1, ping_id: %2").arg(data.vmsg_id.v).arg(data.vping_id.v)); DEBUG_LOG(("Message Info: pong received, msg_id: %1, ping_id: %2").arg(data.vmsg_id().v).arg(data.vping_id().v));
if (!wasSent(data.vmsg_id.v)) { if (!wasSent(data.vmsg_id().v)) {
DEBUG_LOG(("Message Error: such msg_id %1 ping_id %2 was not sent recently").arg(data.vmsg_id.v).arg(data.vping_id.v)); DEBUG_LOG(("Message Error: such msg_id %1 ping_id %2 was not sent recently").arg(data.vmsg_id().v).arg(data.vping_id().v));
return HandleResult::Ignored; return HandleResult::Ignored;
} }
if (data.vping_id.v == _pingId) { if (data.vping_id().v == _pingId) {
_pingId = 0; _pingId = 0;
} else { } else {
DEBUG_LOG(("Message Info: just pong...")); DEBUG_LOG(("Message Info: just pong..."));
} }
QVector<MTPlong> ids(1, data.vmsg_id); QVector<MTPlong> ids(1, data.vmsg_id());
if (badTime) { if (badTime) {
if (requestsFixTimeSalt(ids, serverTime, serverSalt)) { if (requestsFixTimeSalt(ids, serverTime, serverSalt)) {
badTime = false; badTime = false;
@ -2543,10 +2533,7 @@ void ConnectionPrivate::updateAuthKey() {
_authKeyData = std::make_unique<ConnectionPrivate::AuthKeyCreateData>(); _authKeyData = std::make_unique<ConnectionPrivate::AuthKeyCreateData>();
_authKeyStrings = std::make_unique<ConnectionPrivate::AuthKeyCreateStrings>(); _authKeyStrings = std::make_unique<ConnectionPrivate::AuthKeyCreateStrings>();
_authKeyData->nonce = rand_value<MTPint128>(); const auto nonce = _authKeyData->nonce = rand_value<MTPint128>();
MTPReq_pq_multi req_pq;
req_pq.vnonce = _authKeyData->nonce;
connect(_connection, &AbstractConnection::receivedData, [=] { connect(_connection, &AbstractConnection::receivedData, [=] {
pqAnswered(); pqAnswered();
@ -2554,7 +2541,8 @@ void ConnectionPrivate::updateAuthKey() {
DEBUG_LOG(("AuthKey Info: sending Req_pq...")); DEBUG_LOG(("AuthKey Info: sending Req_pq..."));
lockFinished.unlock(); lockFinished.unlock();
sendNotSecureRequest(req_pq);
sendNotSecureRequest(MTPReq_pq_multi(nonce));
} }
void ConnectionPrivate::clearMessages() { void ConnectionPrivate::clearMessages() {
@ -2573,14 +2561,14 @@ void ConnectionPrivate::pqAnswered() {
} }
auto &res_pq_data = res_pq.c_resPQ(); auto &res_pq_data = res_pq.c_resPQ();
if (res_pq_data.vnonce != _authKeyData->nonce) { if (res_pq_data.vnonce() != _authKeyData->nonce) {
LOG(("AuthKey Error: received nonce <> sent nonce (in res_pq)!")); LOG(("AuthKey Error: received nonce <> sent nonce (in res_pq)!"));
DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&res_pq_data.vnonce, 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str())); DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&res_pq_data.vnonce(), 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str()));
return restart(); return restart();
} }
auto rsaKey = internal::RSAPublicKey(); auto rsaKey = internal::RSAPublicKey();
if (!_instance->dcOptions()->getDcRSAKey(BareDcId(_shiftedDcId), res_pq.c_resPQ().vserver_public_key_fingerprints.v, &rsaKey)) { if (!_instance->dcOptions()->getDcRSAKey(BareDcId(_shiftedDcId), res_pq.c_resPQ().vserver_public_key_fingerprints().v, &rsaKey)) {
if (_dcType == DcType::Cdn) { if (_dcType == DcType::Cdn) {
LOG(("Warning: CDN public RSA key not found")); LOG(("Warning: CDN public RSA key not found"));
requestCDNConfig(); requestCDNConfig();
@ -2591,10 +2579,10 @@ void ConnectionPrivate::pqAnswered() {
} }
Assert(rsaKey.isValid()); Assert(rsaKey.isValid());
_authKeyData->server_nonce = res_pq_data.vserver_nonce; _authKeyData->server_nonce = res_pq_data.vserver_nonce();
_authKeyData->new_nonce = rand_value<MTPint256>(); _authKeyData->new_nonce = rand_value<MTPint256>();
auto &pq = res_pq_data.vpq.v; auto &pq = res_pq_data.vpq().v;
auto p = QByteArray(); auto p = QByteArray();
auto q = QByteArray(); auto q = QByteArray();
if (!internal::parsePQ(pq, p, q)) { if (!internal::parsePQ(pq, p, q)) {
@ -2604,7 +2592,7 @@ void ConnectionPrivate::pqAnswered() {
} }
auto p_q_inner = MTP_p_q_inner_data_dc( auto p_q_inner = MTP_p_q_inner_data_dc(
res_pq_data.vpq, res_pq_data.vpq(),
MTP_bytes(std::move(p)), MTP_bytes(std::move(p)),
MTP_bytes(std::move(q)), MTP_bytes(std::move(q)),
_authKeyData->nonce, _authKeyData->nonce,
@ -2622,14 +2610,13 @@ void ConnectionPrivate::pqAnswered() {
DEBUG_LOG(("AuthKey Info: sending Req_DH_params...")); DEBUG_LOG(("AuthKey Info: sending Req_DH_params..."));
MTPReq_DH_params req_DH_params; sendNotSecureRequest(MTPReq_DH_params(
req_DH_params.vnonce = _authKeyData->nonce; _authKeyData->nonce,
req_DH_params.vserver_nonce = _authKeyData->server_nonce; _authKeyData->server_nonce,
req_DH_params.vpublic_key_fingerprint = MTP_long(rsaKey.getFingerPrint()); p_q_inner.c_p_q_inner_data_dc().vp(),
req_DH_params.vp = p_q_inner.c_p_q_inner_data_dc().vp; p_q_inner.c_p_q_inner_data_dc().vq(),
req_DH_params.vq = p_q_inner.c_p_q_inner_data_dc().vq; MTP_long(rsaKey.getFingerPrint()),
req_DH_params.vencrypted_data = MTP_bytes(dhEncString); MTP_bytes(dhEncString)));
sendNotSecureRequest(req_DH_params);
} }
bytes::vector ConnectionPrivate::encryptPQInnerRSA( bytes::vector ConnectionPrivate::encryptPQInnerRSA(
@ -2675,18 +2662,18 @@ void ConnectionPrivate::dhParamsAnswered() {
switch (res_DH_params.type()) { switch (res_DH_params.type()) {
case mtpc_server_DH_params_ok: { case mtpc_server_DH_params_ok: {
const auto &encDH(res_DH_params.c_server_DH_params_ok()); const auto &encDH(res_DH_params.c_server_DH_params_ok());
if (encDH.vnonce != _authKeyData->nonce) { if (encDH.vnonce() != _authKeyData->nonce) {
LOG(("AuthKey Error: received nonce <> sent nonce (in server_DH_params_ok)!")); LOG(("AuthKey Error: received nonce <> sent nonce (in server_DH_params_ok)!"));
DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&encDH.vnonce, 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str())); DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&encDH.vnonce(), 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str()));
return restart(); return restart();
} }
if (encDH.vserver_nonce != _authKeyData->server_nonce) { if (encDH.vserver_nonce() != _authKeyData->server_nonce) {
LOG(("AuthKey Error: received server_nonce <> sent server_nonce (in server_DH_params_ok)!")); LOG(("AuthKey Error: received server_nonce <> sent server_nonce (in server_DH_params_ok)!"));
DEBUG_LOG(("AuthKey Error: received server_nonce: %1, sent server_nonce: %2").arg(Logs::mb(&encDH.vserver_nonce, 16).str()).arg(Logs::mb(&_authKeyData->server_nonce, 16).str())); DEBUG_LOG(("AuthKey Error: received server_nonce: %1, sent server_nonce: %2").arg(Logs::mb(&encDH.vserver_nonce(), 16).str()).arg(Logs::mb(&_authKeyData->server_nonce, 16).str()));
return restart(); return restart();
} }
auto &encDHStr = encDH.vencrypted_answer.v; auto &encDHStr = encDH.vencrypted_answer().v;
uint32 encDHLen = encDHStr.length(), encDHBufLen = encDHLen >> 2; uint32 encDHLen = encDHStr.length(), encDHBufLen = encDHLen >> 2;
if ((encDHLen & 0x03) || encDHBufLen < 6) { if ((encDHLen & 0x03) || encDHBufLen < 6) {
LOG(("AuthKey Error: bad encrypted data length %1 (in server_DH_params_ok)!").arg(encDHLen)); LOG(("AuthKey Error: bad encrypted data length %1 (in server_DH_params_ok)!").arg(encDHLen));
@ -2719,14 +2706,14 @@ void ConnectionPrivate::dhParamsAnswered() {
MTPServer_DH_inner_data dh_inner; MTPServer_DH_inner_data dh_inner;
dh_inner.read(to, end); dh_inner.read(to, end);
const auto &dh_inner_data(dh_inner.c_server_DH_inner_data()); const auto &dh_inner_data(dh_inner.c_server_DH_inner_data());
if (dh_inner_data.vnonce != _authKeyData->nonce) { if (dh_inner_data.vnonce() != _authKeyData->nonce) {
LOG(("AuthKey Error: received nonce <> sent nonce (in server_DH_inner_data)!")); LOG(("AuthKey Error: received nonce <> sent nonce (in server_DH_inner_data)!"));
DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&dh_inner_data.vnonce, 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str())); DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&dh_inner_data.vnonce(), 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str()));
return restart(); return restart();
} }
if (dh_inner_data.vserver_nonce != _authKeyData->server_nonce) { if (dh_inner_data.vserver_nonce() != _authKeyData->server_nonce) {
LOG(("AuthKey Error: received server_nonce <> sent server_nonce (in server_DH_inner_data)!")); LOG(("AuthKey Error: received server_nonce <> sent server_nonce (in server_DH_inner_data)!"));
DEBUG_LOG(("AuthKey Error: received server_nonce: %1, sent server_nonce: %2").arg(Logs::mb(&dh_inner_data.vserver_nonce, 16).str()).arg(Logs::mb(&_authKeyData->server_nonce, 16).str())); DEBUG_LOG(("AuthKey Error: received server_nonce: %1, sent server_nonce: %2").arg(Logs::mb(&dh_inner_data.vserver_nonce(), 16).str()).arg(Logs::mb(&_authKeyData->server_nonce, 16).str()));
return restart(); return restart();
} }
uchar sha1Buffer[20]; uchar sha1Buffer[20];
@ -2735,38 +2722,38 @@ void ConnectionPrivate::dhParamsAnswered() {
DEBUG_LOG(("AuthKey Error: sha1 did not match, server_nonce: %1, new_nonce %2, encrypted data %3").arg(Logs::mb(&_authKeyData->server_nonce, 16).str()).arg(Logs::mb(&_authKeyData->new_nonce, 16).str()).arg(Logs::mb(encDHStr.constData(), encDHLen).str())); DEBUG_LOG(("AuthKey Error: sha1 did not match, server_nonce: %1, new_nonce %2, encrypted data %3").arg(Logs::mb(&_authKeyData->server_nonce, 16).str()).arg(Logs::mb(&_authKeyData->new_nonce, 16).str()).arg(Logs::mb(encDHStr.constData(), encDHLen).str()));
return restart(); return restart();
} }
unixtimeSet(dh_inner_data.vserver_time.v); unixtimeSet(dh_inner_data.vserver_time().v);
// check that dhPrime and (dhPrime - 1) / 2 are really prime // check that dhPrime and (dhPrime - 1) / 2 are really prime
if (!IsPrimeAndGood(bytes::make_span(dh_inner_data.vdh_prime.v), dh_inner_data.vg.v)) { if (!IsPrimeAndGood(bytes::make_span(dh_inner_data.vdh_prime().v), dh_inner_data.vg().v)) {
LOG(("AuthKey Error: bad dh_prime primality!")); LOG(("AuthKey Error: bad dh_prime primality!"));
return restart(); return restart();
} }
_authKeyStrings->dh_prime = bytes::make_vector( _authKeyStrings->dh_prime = bytes::make_vector(
dh_inner_data.vdh_prime.v); dh_inner_data.vdh_prime().v);
_authKeyData->g = dh_inner_data.vg.v; _authKeyData->g = dh_inner_data.vg().v;
_authKeyStrings->g_a = bytes::make_vector(dh_inner_data.vg_a.v); _authKeyStrings->g_a = bytes::make_vector(dh_inner_data.vg_a().v);
_authKeyData->retry_id = MTP_long(0); _authKeyData->retry_id = MTP_long(0);
_authKeyData->retries = 0; _authKeyData->retries = 0;
} return dhClientParamsSend(); } return dhClientParamsSend();
case mtpc_server_DH_params_fail: { case mtpc_server_DH_params_fail: {
const auto &encDH(res_DH_params.c_server_DH_params_fail()); const auto &encDH(res_DH_params.c_server_DH_params_fail());
if (encDH.vnonce != _authKeyData->nonce) { if (encDH.vnonce() != _authKeyData->nonce) {
LOG(("AuthKey Error: received nonce <> sent nonce (in server_DH_params_fail)!")); LOG(("AuthKey Error: received nonce <> sent nonce (in server_DH_params_fail)!"));
DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&encDH.vnonce, 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str())); DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&encDH.vnonce(), 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str()));
return restart(); return restart();
} }
if (encDH.vserver_nonce != _authKeyData->server_nonce) { if (encDH.vserver_nonce() != _authKeyData->server_nonce) {
LOG(("AuthKey Error: received server_nonce <> sent server_nonce (in server_DH_params_fail)!")); LOG(("AuthKey Error: received server_nonce <> sent server_nonce (in server_DH_params_fail)!"));
DEBUG_LOG(("AuthKey Error: received server_nonce: %1, sent server_nonce: %2").arg(Logs::mb(&encDH.vserver_nonce, 16).str()).arg(Logs::mb(&_authKeyData->server_nonce, 16).str())); DEBUG_LOG(("AuthKey Error: received server_nonce: %1, sent server_nonce: %2").arg(Logs::mb(&encDH.vserver_nonce(), 16).str()).arg(Logs::mb(&_authKeyData->server_nonce, 16).str()));
return restart(); return restart();
} }
uchar sha1Buffer[20]; uchar sha1Buffer[20];
if (encDH.vnew_nonce_hash != *(MTPint128*)(hashSha1(&_authKeyData->new_nonce, 32, sha1Buffer) + 1)) { if (encDH.vnew_nonce_hash() != *(MTPint128*)(hashSha1(&_authKeyData->new_nonce, 32, sha1Buffer) + 1)) {
LOG(("AuthKey Error: received new_nonce_hash did not match!")); LOG(("AuthKey Error: received new_nonce_hash did not match!"));
DEBUG_LOG(("AuthKey Error: received new_nonce_hash: %1, new_nonce: %2").arg(Logs::mb(&encDH.vnew_nonce_hash, 16).str()).arg(Logs::mb(&_authKeyData->new_nonce, 32).str())); DEBUG_LOG(("AuthKey Error: received new_nonce_hash: %1, new_nonce: %2").arg(Logs::mb(&encDH.vnew_nonce_hash(), 16).str()).arg(Logs::mb(&_authKeyData->new_nonce, 32).str()));
return restart(); return restart();
} }
LOG(("AuthKey Error: server_DH_params_fail received!")); LOG(("AuthKey Error: server_DH_params_fail received!"));
@ -2812,13 +2799,11 @@ void ConnectionPrivate::dhClientParamsSend() {
dhClientParamsAnswered(); dhClientParamsAnswered();
}); });
MTPSet_client_DH_params req_client_DH_params;
req_client_DH_params.vnonce = _authKeyData->nonce;
req_client_DH_params.vserver_nonce = _authKeyData->server_nonce;
req_client_DH_params.vencrypted_data = MTP_string(std::move(sdhEncString));
DEBUG_LOG(("AuthKey Info: sending Req_client_DH_params...")); DEBUG_LOG(("AuthKey Info: sending Req_client_DH_params..."));
sendNotSecureRequest(req_client_DH_params); sendNotSecureRequest(MTPSet_client_DH_params(
_authKeyData->nonce,
_authKeyData->server_nonce,
MTP_string(std::move(sdhEncString))));
} }
std::string ConnectionPrivate::encryptClientDHInner(const MTPClient_DH_Inner_Data &data) { std::string ConnectionPrivate::encryptClientDHInner(const MTPClient_DH_Inner_Data &data) {
@ -2863,25 +2848,25 @@ void ConnectionPrivate::dhClientParamsAnswered() {
switch (res_client_DH_params.type()) { switch (res_client_DH_params.type()) {
case mtpc_dh_gen_ok: { case mtpc_dh_gen_ok: {
const auto &resDH(res_client_DH_params.c_dh_gen_ok()); const auto &resDH(res_client_DH_params.c_dh_gen_ok());
if (resDH.vnonce != _authKeyData->nonce) { if (resDH.vnonce() != _authKeyData->nonce) {
LOG(("AuthKey Error: received nonce <> sent nonce (in dh_gen_ok)!")); LOG(("AuthKey Error: received nonce <> sent nonce (in dh_gen_ok)!"));
DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&resDH.vnonce, 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str())); DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&resDH.vnonce(), 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str()));
lockFinished.unlock(); lockFinished.unlock();
return restart(); return restart();
} }
if (resDH.vserver_nonce != _authKeyData->server_nonce) { if (resDH.vserver_nonce() != _authKeyData->server_nonce) {
LOG(("AuthKey Error: received server_nonce <> sent server_nonce (in dh_gen_ok)!")); LOG(("AuthKey Error: received server_nonce <> sent server_nonce (in dh_gen_ok)!"));
DEBUG_LOG(("AuthKey Error: received server_nonce: %1, sent server_nonce: %2").arg(Logs::mb(&resDH.vserver_nonce, 16).str()).arg(Logs::mb(&_authKeyData->server_nonce, 16).str())); DEBUG_LOG(("AuthKey Error: received server_nonce: %1, sent server_nonce: %2").arg(Logs::mb(&resDH.vserver_nonce(), 16).str()).arg(Logs::mb(&_authKeyData->server_nonce, 16).str()));
lockFinished.unlock(); lockFinished.unlock();
return restart(); return restart();
} }
_authKeyData->new_nonce_buf[32] = 1; _authKeyData->new_nonce_buf[32] = 1;
uchar sha1Buffer[20]; uchar sha1Buffer[20];
if (resDH.vnew_nonce_hash1 != *(MTPint128*)(hashSha1(_authKeyData->new_nonce_buf, 41, sha1Buffer) + 1)) { if (resDH.vnew_nonce_hash1() != *(MTPint128*)(hashSha1(_authKeyData->new_nonce_buf, 41, sha1Buffer) + 1)) {
LOG(("AuthKey Error: received new_nonce_hash1 did not match!")); LOG(("AuthKey Error: received new_nonce_hash1 did not match!"));
DEBUG_LOG(("AuthKey Error: received new_nonce_hash1: %1, new_nonce_buf: %2").arg(Logs::mb(&resDH.vnew_nonce_hash1, 16).str()).arg(Logs::mb(_authKeyData->new_nonce_buf, 41).str())); DEBUG_LOG(("AuthKey Error: received new_nonce_hash1: %1, new_nonce_buf: %2").arg(Logs::mb(&resDH.vnew_nonce_hash1(), 16).str()).arg(Logs::mb(_authKeyData->new_nonce_buf, 41).str()));
lockFinished.unlock(); lockFinished.unlock();
return restart(); return restart();
@ -2901,25 +2886,25 @@ void ConnectionPrivate::dhClientParamsAnswered() {
case mtpc_dh_gen_retry: { case mtpc_dh_gen_retry: {
const auto &resDH(res_client_DH_params.c_dh_gen_retry()); const auto &resDH(res_client_DH_params.c_dh_gen_retry());
if (resDH.vnonce != _authKeyData->nonce) { if (resDH.vnonce() != _authKeyData->nonce) {
LOG(("AuthKey Error: received nonce <> sent nonce (in dh_gen_retry)!")); LOG(("AuthKey Error: received nonce <> sent nonce (in dh_gen_retry)!"));
DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&resDH.vnonce, 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str())); DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&resDH.vnonce(), 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str()));
lockFinished.unlock(); lockFinished.unlock();
return restart(); return restart();
} }
if (resDH.vserver_nonce != _authKeyData->server_nonce) { if (resDH.vserver_nonce() != _authKeyData->server_nonce) {
LOG(("AuthKey Error: received server_nonce <> sent server_nonce (in dh_gen_retry)!")); LOG(("AuthKey Error: received server_nonce <> sent server_nonce (in dh_gen_retry)!"));
DEBUG_LOG(("AuthKey Error: received server_nonce: %1, sent server_nonce: %2").arg(Logs::mb(&resDH.vserver_nonce, 16).str()).arg(Logs::mb(&_authKeyData->server_nonce, 16).str())); DEBUG_LOG(("AuthKey Error: received server_nonce: %1, sent server_nonce: %2").arg(Logs::mb(&resDH.vserver_nonce(), 16).str()).arg(Logs::mb(&_authKeyData->server_nonce, 16).str()));
lockFinished.unlock(); lockFinished.unlock();
return restart(); return restart();
} }
_authKeyData->new_nonce_buf[32] = 2; _authKeyData->new_nonce_buf[32] = 2;
uchar sha1Buffer[20]; uchar sha1Buffer[20];
if (resDH.vnew_nonce_hash2 != *(MTPint128*)(hashSha1(_authKeyData->new_nonce_buf, 41, sha1Buffer) + 1)) { if (resDH.vnew_nonce_hash2() != *(MTPint128*)(hashSha1(_authKeyData->new_nonce_buf, 41, sha1Buffer) + 1)) {
LOG(("AuthKey Error: received new_nonce_hash2 did not match!")); LOG(("AuthKey Error: received new_nonce_hash2 did not match!"));
DEBUG_LOG(("AuthKey Error: received new_nonce_hash2: %1, new_nonce_buf: %2").arg(Logs::mb(&resDH.vnew_nonce_hash2, 16).str()).arg(Logs::mb(_authKeyData->new_nonce_buf, 41).str())); DEBUG_LOG(("AuthKey Error: received new_nonce_hash2: %1, new_nonce_buf: %2").arg(Logs::mb(&resDH.vnew_nonce_hash2(), 16).str()).arg(Logs::mb(_authKeyData->new_nonce_buf, 41).str()));
lockFinished.unlock(); lockFinished.unlock();
return restart(); return restart();
@ -2929,25 +2914,25 @@ void ConnectionPrivate::dhClientParamsAnswered() {
case mtpc_dh_gen_fail: { case mtpc_dh_gen_fail: {
const auto &resDH(res_client_DH_params.c_dh_gen_fail()); const auto &resDH(res_client_DH_params.c_dh_gen_fail());
if (resDH.vnonce != _authKeyData->nonce) { if (resDH.vnonce() != _authKeyData->nonce) {
LOG(("AuthKey Error: received nonce <> sent nonce (in dh_gen_fail)!")); LOG(("AuthKey Error: received nonce <> sent nonce (in dh_gen_fail)!"));
DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&resDH.vnonce, 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str())); DEBUG_LOG(("AuthKey Error: received nonce: %1, sent nonce: %2").arg(Logs::mb(&resDH.vnonce(), 16).str()).arg(Logs::mb(&_authKeyData->nonce, 16).str()));
lockFinished.unlock(); lockFinished.unlock();
return restart(); return restart();
} }
if (resDH.vserver_nonce != _authKeyData->server_nonce) { if (resDH.vserver_nonce() != _authKeyData->server_nonce) {
LOG(("AuthKey Error: received server_nonce <> sent server_nonce (in dh_gen_fail)!")); LOG(("AuthKey Error: received server_nonce <> sent server_nonce (in dh_gen_fail)!"));
DEBUG_LOG(("AuthKey Error: received server_nonce: %1, sent server_nonce: %2").arg(Logs::mb(&resDH.vserver_nonce, 16).str()).arg(Logs::mb(&_authKeyData->server_nonce, 16).str())); DEBUG_LOG(("AuthKey Error: received server_nonce: %1, sent server_nonce: %2").arg(Logs::mb(&resDH.vserver_nonce(), 16).str()).arg(Logs::mb(&_authKeyData->server_nonce, 16).str()));
lockFinished.unlock(); lockFinished.unlock();
return restart(); return restart();
} }
_authKeyData->new_nonce_buf[32] = 3; _authKeyData->new_nonce_buf[32] = 3;
uchar sha1Buffer[20]; uchar sha1Buffer[20];
if (resDH.vnew_nonce_hash3 != *(MTPint128*)(hashSha1(_authKeyData->new_nonce_buf, 41, sha1Buffer) + 1)) { if (resDH.vnew_nonce_hash3() != *(MTPint128*)(hashSha1(_authKeyData->new_nonce_buf, 41, sha1Buffer) + 1)) {
LOG(("AuthKey Error: received new_nonce_hash3 did not match!")); LOG(("AuthKey Error: received new_nonce_hash3 did not match!"));
DEBUG_LOG(("AuthKey Error: received new_nonce_hash3: %1, new_nonce_buf: %2").arg(Logs::mb(&resDH.vnew_nonce_hash3, 16).str()).arg(Logs::mb(_authKeyData->new_nonce_buf, 41).str())); DEBUG_LOG(("AuthKey Error: received new_nonce_hash3: %1, new_nonce_buf: %2").arg(Logs::mb(&resDH.vnew_nonce_hash3(), 16).str()).arg(Logs::mb(_authKeyData->new_nonce_buf, 41).str()));
lockFinished.unlock(); lockFinished.unlock();
return restart(); return restart();

View file

@ -171,7 +171,7 @@ void HttpConnection::requestFinished(QNetworkReply *reply) {
try { try {
const auto res_pq = readPQFakeReply(data); const auto res_pq = readPQFakeReply(data);
const auto &data = res_pq.c_resPQ(); const auto &data = res_pq.c_resPQ();
if (data.vnonce == _checkNonce) { if (data.vnonce() == _checkNonce) {
DEBUG_LOG(("Connection Info: " DEBUG_LOG(("Connection Info: "
"HTTP-transport to %1 connected by pq-response" "HTTP-transport to %1 connected by pq-response"
).arg(_address)); ).arg(_address));

View file

@ -638,7 +638,7 @@ void TcpConnection::socketPacket(bytes::const_span bytes) {
try { try {
const auto res_pq = readPQFakeReply(data); const auto res_pq = readPQFakeReply(data);
const auto &data = res_pq.c_resPQ(); const auto &data = res_pq.c_resPQ();
if (data.vnonce == _checkNonce) { if (data.vnonce() == _checkNonce) {
DEBUG_LOG(("Connection Info: Valid pq response by TCP.")); DEBUG_LOG(("Connection Info: Valid pq response by TCP."));
_status = Status::Ready; _status = Status::Ready;
disconnect( disconnect(

View file

@ -369,6 +369,49 @@ SecureRequest SecureRequest::Serialize(const Request &request) {
return serialized; return serialized;
} }
template <typename Type>
struct RepeatHelper {
using type = Type;
};
template <typename Type>
using Repeat = typename RepeatHelper<Type>::type;
template <typename Type>
class conditional {
public:
conditional() = default;
conditional(const Type *value) : _value(value) {
}
operator const Type*() const {
return _value;
}
const Type *operator->() const {
Expects(_value != nullptr);
return _value;
}
const Type &operator*() const {
Expects(_value != nullptr);
return *_value;
}
template <typename Inner = std::decay_t<decltype(std::declval<Type>().v)>>
Inner value_or(Repeat<Inner> fallback) const {
return _value ? _value->v : fallback;
}
template <typename Inner = std::decay_t<decltype(std::declval<Type>().v)>>
Inner value_or_empty() const {
return _value ? _value->v : Inner();
}
private:
const Type *_value = nullptr;
};
} // namespace MTP } // namespace MTP
class MTPint { class MTPint {
@ -660,9 +703,11 @@ private:
friend MTPstring MTP_string(const std::string &v); friend MTPstring MTP_string(const std::string &v);
friend MTPstring MTP_string(const QString &v); friend MTPstring MTP_string(const QString &v);
friend MTPstring MTP_string(const char *v); friend MTPstring MTP_string(const char *v);
friend MTPstring MTP_string();
friend MTPbytes MTP_bytes(const QByteArray &v); friend MTPbytes MTP_bytes(const QByteArray &v);
friend MTPbytes MTP_bytes(QByteArray &&v); friend MTPbytes MTP_bytes(QByteArray &&v);
friend MTPbytes MTP_bytes();
}; };
using MTPString = MTPBoxed<MTPstring>; using MTPString = MTPBoxed<MTPstring>;
@ -677,6 +722,9 @@ inline MTPstring MTP_string(const QString &v) {
inline MTPstring MTP_string(const char *v) { inline MTPstring MTP_string(const char *v) {
return MTPstring(QByteArray(v, strlen(v))); return MTPstring(QByteArray(v, strlen(v)));
} }
inline MTPstring MTP_string() {
return MTPstring(QByteArray());
}
MTPstring MTP_string(const QByteArray &v) = delete; MTPstring MTP_string(const QByteArray &v) = delete;
inline MTPbytes MTP_bytes(const QByteArray &v) { inline MTPbytes MTP_bytes(const QByteArray &v) {
@ -685,6 +733,9 @@ inline MTPbytes MTP_bytes(const QByteArray &v) {
inline MTPbytes MTP_bytes(QByteArray &&v) { inline MTPbytes MTP_bytes(QByteArray &&v) {
return MTPbytes(std::move(v)); return MTPbytes(std::move(v));
} }
inline MTPbytes MTP_bytes() {
return MTPbytes(QByteArray());
}
inline MTPbytes MTP_bytes(bytes::const_span buffer) { inline MTPbytes MTP_bytes(bytes::const_span buffer) {
return MTP_bytes(QByteArray( return MTP_bytes(QByteArray(
reinterpret_cast<const char*>(buffer.data()), reinterpret_cast<const char*>(buffer.data()),
@ -705,6 +756,10 @@ inline QString qs(const MTPstring &v) {
return QString::fromUtf8(v.v); return QString::fromUtf8(v.v);
} }
inline QString qs(const QByteArray &v) {
return QString::fromUtf8(v);
}
inline QByteArray qba(const MTPstring &v) { inline QByteArray qba(const MTPstring &v) {
return v.v; return v.v;
} }
@ -756,6 +811,8 @@ private:
friend MTPvector<U> MTP_vector(const QVector<U> &v); friend MTPvector<U> MTP_vector(const QVector<U> &v);
template <typename U> template <typename U>
friend MTPvector<U> MTP_vector(QVector<U> &&v); friend MTPvector<U> MTP_vector(QVector<U> &&v);
template <typename U>
friend MTPvector<U> MTP_vector();
}; };
template <typename T> template <typename T>
@ -775,6 +832,10 @@ inline MTPvector<T> MTP_vector(QVector<T> &&v) {
return MTPvector<T>(std::move(v)); return MTPvector<T>(std::move(v));
} }
template <typename T> template <typename T>
inline MTPvector<T> MTP_vector() {
return MTPvector<T>();
}
template <typename T>
using MTPVector = MTPBoxed<MTPvector<T>>; using MTPVector = MTPBoxed<MTPvector<T>>;
template <typename T> template <typename T>

View file

@ -146,15 +146,13 @@ void DcOptions::processFromList(
} }
auto &option = mtpOption.c_dcOption(); auto &option = mtpOption.c_dcOption();
auto dcId = option.vid.v; auto dcId = option.vid().v;
auto flags = option.vflags.v; auto flags = option.vflags().v;
auto ip = std::string( auto ip = std::string(
option.vip_address.v.constData(), option.vip_address().v.constData(),
option.vip_address.v.size()); option.vip_address().v.size());
auto port = option.vport.v; auto port = option.vport().v;
auto secret = option.has_secret() auto secret = bytes::make_vector(option.vsecret().value_or_empty());
? bytes::make_vector(option.vsecret.v)
: bytes::vector();
ApplyOneOption(data, dcId, flags, ip, port, secret); ApplyOneOption(data, dcId, flags, ip, port, secret);
} }
@ -537,18 +535,18 @@ DcType DcOptions::dcType(ShiftedDcId shiftedDcId) const {
void DcOptions::setCDNConfig(const MTPDcdnConfig &config) { void DcOptions::setCDNConfig(const MTPDcdnConfig &config) {
WriteLocker lock(this); WriteLocker lock(this);
_cdnPublicKeys.clear(); _cdnPublicKeys.clear();
for_const (auto &publicKey, config.vpublic_keys.v) { for_const (auto &publicKey, config.vpublic_keys().v) {
Expects(publicKey.type() == mtpc_cdnPublicKey); Expects(publicKey.type() == mtpc_cdnPublicKey);
const auto &keyData = publicKey.c_cdnPublicKey(); const auto &keyData = publicKey.c_cdnPublicKey();
const auto keyBytes = bytes::make_span(keyData.vpublic_key.v); const auto keyBytes = bytes::make_span(keyData.vpublic_key().v);
auto key = internal::RSAPublicKey(keyBytes); auto key = internal::RSAPublicKey(keyBytes);
if (key.isValid()) { if (key.isValid()) {
_cdnPublicKeys[keyData.vdc_id.v].emplace( _cdnPublicKeys[keyData.vdc_id().v].emplace(
key.getFingerPrint(), key.getFingerPrint(),
std::move(key)); std::move(key));
} else { } else {
LOG(("MTP Error: could not read this public RSA key:")); LOG(("MTP Error: could not read this public RSA key:"));
LOG((qs(keyData.vpublic_key))); LOG((qs(keyData.vpublic_key())));
} }
} }
} }

View file

@ -17,14 +17,14 @@ namespace {
std::optional<MTPInputChannel> ExtractChannel( std::optional<MTPInputChannel> ExtractChannel(
const MTPcontacts_ResolvedPeer &result) { const MTPcontacts_ResolvedPeer &result) {
const auto &data = result.c_contacts_resolvedPeer(); const auto &data = result.c_contacts_resolvedPeer();
if (const auto peer = peerFromMTP(data.vpeer)) { if (const auto peer = peerFromMTP(data.vpeer())) {
for (const auto &chat : data.vchats.v) { for (const auto &chat : data.vchats().v) {
if (chat.type() == mtpc_channel) { if (chat.type() == mtpc_channel) {
const auto &channel = chat.c_channel(); const auto &channel = chat.c_channel();
if (peer == peerFromChannel(channel.vid)) { if (peer == peerFromChannel(channel.vid())) {
return MTP_inputChannel( return MTP_inputChannel(
channel.vid, channel.vid(),
channel.vaccess_hash); MTP_long(channel.vaccess_hash().value_or_empty()));
} }
} }
} }
@ -40,23 +40,23 @@ std::optional<DedicatedLoader::File> ParseFile(
return std::nullopt; return std::nullopt;
} }
const auto &data = message->c_message(); const auto &data = message->c_message();
if (!data.has_media() const auto media = data.vmedia();
|| data.vmedia.type() != mtpc_messageMediaDocument) { if (!media || media->type() != mtpc_messageMediaDocument) {
LOG(("Update Error: MTP file media not found.")); LOG(("Update Error: MTP file media not found."));
return std::nullopt; return std::nullopt;
} }
const auto &document = data.vmedia.c_messageMediaDocument(); const auto &inner = media->c_messageMediaDocument();
if (!document.has_document() const auto document = inner.vdocument();
|| document.vdocument.type() != mtpc_document) { if (!document || document->type() != mtpc_document) {
LOG(("Update Error: MTP file not found.")); LOG(("Update Error: MTP file not found."));
return std::nullopt; return std::nullopt;
} }
const auto &fields = document.vdocument.c_document(); const auto &fields = document->c_document();
const auto name = [&] { const auto name = [&] {
for (const auto &attribute : fields.vattributes.v) { for (const auto &attribute : fields.vattributes().v) {
if (attribute.type() == mtpc_documentAttributeFilename) { if (attribute.type() == mtpc_documentAttributeFilename) {
const auto &data = attribute.c_documentAttributeFilename(); const auto &data = attribute.c_documentAttributeFilename();
return qs(data.vfile_name); return qs(data.vfile_name());
} }
} }
return QString(); return QString();
@ -65,17 +65,17 @@ std::optional<DedicatedLoader::File> ParseFile(
LOG(("Update Error: MTP file name not found.")); LOG(("Update Error: MTP file name not found."));
return std::nullopt; return std::nullopt;
} }
const auto size = fields.vsize.v; const auto size = fields.vsize().v;
if (size <= 0) { if (size <= 0) {
LOG(("Update Error: MTP file size is invalid.")); LOG(("Update Error: MTP file size is invalid."));
return std::nullopt; return std::nullopt;
} }
const auto location = MTP_inputDocumentFileLocation( const auto location = MTP_inputDocumentFileLocation(
fields.vid, fields.vid(),
fields.vaccess_hash, fields.vaccess_hash(),
fields.vfile_reference, fields.vfile_reference(),
MTP_string(QString())); MTP_string());
return DedicatedLoader::File{ name, size, fields.vdc_id.v, location }; return DedicatedLoader::File{ name, size, fields.vdc_id().v, location };
} }
} // namespace } // namespace
@ -329,7 +329,7 @@ void DedicatedLoader::gotPart(int offset, const MTPupload_File &result) {
return; return;
} }
const auto &data = result.c_upload_file(); const auto &data = result.c_upload_file();
if (data.vbytes.v.isEmpty()) { if (data.vbytes().v.isEmpty()) {
LOG(("Update Error: MTP empty part received.")); LOG(("Update Error: MTP empty part received."));
threadSafeFailed(); threadSafeFailed();
return; return;
@ -341,7 +341,7 @@ void DedicatedLoader::gotPart(int offset, const MTPupload_File &result) {
[](const Request &request) { return request.offset; }); [](const Request &request) { return request.offset; });
Assert(i != end(_requests)); Assert(i != end(_requests));
i->bytes = data.vbytes.v; i->bytes = data.vbytes().v;
while (!_requests.empty() && !_requests.front().bytes.isEmpty()) { while (!_requests.empty() && !_requests.front().bytes.isEmpty()) {
writeChunk(bytes::make_span(_requests.front().bytes), _size); writeChunk(bytes::make_span(_requests.front().bytes), _size);
_requests.pop_front(); _requests.pop_front();
@ -415,9 +415,9 @@ std::optional<MTPMessage> GetMessagesElement(
return list.match([&](const MTPDmessages_messagesNotModified &) { return list.match([&](const MTPDmessages_messagesNotModified &) {
return std::optional<MTPMessage>(std::nullopt); return std::optional<MTPMessage>(std::nullopt);
}, [&](const auto &data) { }, [&](const auto &data) {
return data.vmessages.v.isEmpty() return data.vmessages().v.isEmpty()
? std::nullopt ? std::nullopt
: std::make_optional(data.vmessages.v[0]); : std::make_optional(data.vmessages().v[0]);
}); });
} }

View file

@ -748,71 +748,65 @@ void Instance::Private::configLoadDone(const MTPConfig &result) {
_lastConfigLoadedTime = crl::now(); _lastConfigLoadedTime = crl::now();
const auto &data = result.c_config(); const auto &data = result.c_config();
DEBUG_LOG(("MTP Info: got config, chat_size_max: %1, date: %2, test_mode: %3, this_dc: %4, dc_options.length: %5").arg(data.vchat_size_max.v).arg(data.vdate.v).arg(mtpIsTrue(data.vtest_mode)).arg(data.vthis_dc.v).arg(data.vdc_options.v.size())); DEBUG_LOG(("MTP Info: got config, chat_size_max: %1, date: %2, test_mode: %3, this_dc: %4, dc_options.length: %5").arg(data.vchat_size_max().v).arg(data.vdate().v).arg(mtpIsTrue(data.vtest_mode())).arg(data.vthis_dc().v).arg(data.vdc_options().v.size()));
if (data.vdc_options.v.empty()) { if (data.vdc_options().v.empty()) {
LOG(("MTP Error: config with empty dc_options received!")); LOG(("MTP Error: config with empty dc_options received!"));
} else { } else {
_dcOptions->setFromList(data.vdc_options); _dcOptions->setFromList(data.vdc_options());
} }
Global::SetChatSizeMax(data.vchat_size_max.v); Global::SetChatSizeMax(data.vchat_size_max().v);
Global::SetMegagroupSizeMax(data.vmegagroup_size_max.v); Global::SetMegagroupSizeMax(data.vmegagroup_size_max().v);
Global::SetForwardedCountMax(data.vforwarded_count_max.v); Global::SetForwardedCountMax(data.vforwarded_count_max().v);
Global::SetOnlineUpdatePeriod(data.vonline_update_period_ms.v); Global::SetOnlineUpdatePeriod(data.vonline_update_period_ms().v);
Global::SetOfflineBlurTimeout(data.voffline_blur_timeout_ms.v); Global::SetOfflineBlurTimeout(data.voffline_blur_timeout_ms().v);
Global::SetOfflineIdleTimeout(data.voffline_idle_timeout_ms.v); Global::SetOfflineIdleTimeout(data.voffline_idle_timeout_ms().v);
Global::SetOnlineCloudTimeout(data.vonline_cloud_timeout_ms.v); Global::SetOnlineCloudTimeout(data.vonline_cloud_timeout_ms().v);
Global::SetNotifyCloudDelay(data.vnotify_cloud_delay_ms.v); Global::SetNotifyCloudDelay(data.vnotify_cloud_delay_ms().v);
Global::SetNotifyDefaultDelay(data.vnotify_default_delay_ms.v); Global::SetNotifyDefaultDelay(data.vnotify_default_delay_ms().v);
Global::SetPushChatPeriod(data.vpush_chat_period_ms.v); Global::SetPushChatPeriod(data.vpush_chat_period_ms().v);
Global::SetPushChatLimit(data.vpush_chat_limit.v); Global::SetPushChatLimit(data.vpush_chat_limit().v);
Global::SetSavedGifsLimit(data.vsaved_gifs_limit.v); Global::SetSavedGifsLimit(data.vsaved_gifs_limit().v);
Global::SetEditTimeLimit(data.vedit_time_limit.v); Global::SetEditTimeLimit(data.vedit_time_limit().v);
Global::SetRevokeTimeLimit(data.vrevoke_time_limit.v); Global::SetRevokeTimeLimit(data.vrevoke_time_limit().v);
Global::SetRevokePrivateTimeLimit(data.vrevoke_pm_time_limit.v); Global::SetRevokePrivateTimeLimit(data.vrevoke_pm_time_limit().v);
Global::SetRevokePrivateInbox(data.is_revoke_pm_inbox()); Global::SetRevokePrivateInbox(data.is_revoke_pm_inbox());
Global::SetStickersRecentLimit(data.vstickers_recent_limit.v); Global::SetStickersRecentLimit(data.vstickers_recent_limit().v);
Global::SetStickersFavedLimit(data.vstickers_faved_limit.v); Global::SetStickersFavedLimit(data.vstickers_faved_limit().v);
Global::SetPinnedDialogsCountMax( Global::SetPinnedDialogsCountMax(
std::max(data.vpinned_dialogs_count_max.v, 1)); std::max(data.vpinned_dialogs_count_max().v, 1));
Global::SetPinnedDialogsInFolderMax( Global::SetPinnedDialogsInFolderMax(
std::max(data.vpinned_infolder_count_max.v, 1)); std::max(data.vpinned_infolder_count_max().v, 1));
Core::App().setInternalLinkDomain(qs(data.vme_url_prefix)); Core::App().setInternalLinkDomain(qs(data.vme_url_prefix()));
Global::SetChannelsReadMediaPeriod(data.vchannels_read_media_period.v); Global::SetChannelsReadMediaPeriod(data.vchannels_read_media_period().v);
Global::SetWebFileDcId(data.vwebfile_dc_id.v); Global::SetWebFileDcId(data.vwebfile_dc_id().v);
Global::SetTxtDomainString(qs(data.vdc_txt_domain_name)); Global::SetTxtDomainString(qs(data.vdc_txt_domain_name()));
Global::SetCallReceiveTimeoutMs(data.vcall_receive_timeout_ms.v); Global::SetCallReceiveTimeoutMs(data.vcall_receive_timeout_ms().v);
Global::SetCallRingTimeoutMs(data.vcall_ring_timeout_ms.v); Global::SetCallRingTimeoutMs(data.vcall_ring_timeout_ms().v);
Global::SetCallConnectTimeoutMs(data.vcall_connect_timeout_ms.v); Global::SetCallConnectTimeoutMs(data.vcall_connect_timeout_ms().v);
Global::SetCallPacketTimeoutMs(data.vcall_packet_timeout_ms.v); Global::SetCallPacketTimeoutMs(data.vcall_packet_timeout_ms().v);
if (Global::PhoneCallsEnabled() != data.is_phonecalls_enabled()) { if (Global::PhoneCallsEnabled() != data.is_phonecalls_enabled()) {
Global::SetPhoneCallsEnabled(data.is_phonecalls_enabled()); Global::SetPhoneCallsEnabled(data.is_phonecalls_enabled());
Global::RefPhoneCallsEnabledChanged().notify(); Global::RefPhoneCallsEnabledChanged().notify();
} }
Global::SetBlockedMode(data.is_blocked_mode()); Global::SetBlockedMode(data.is_blocked_mode());
Global::SetCaptionLengthMax(data.vcaption_length_max.v); Global::SetCaptionLengthMax(data.vcaption_length_max().v);
const auto lang = data.has_suggested_lang_code() const auto lang = qs(data.vsuggested_lang_code().value_or_empty());
? qs(data.vsuggested_lang_code)
: QString();
Lang::CurrentCloudManager().setSuggestedLanguage(lang); Lang::CurrentCloudManager().setSuggestedLanguage(lang);
Lang::CurrentCloudManager().setCurrentVersions( Lang::CurrentCloudManager().setCurrentVersions(
(data.has_lang_pack_version() data.vlang_pack_version().value_or_empty(),
? data.vlang_pack_version.v data.vbase_lang_pack_version().value_or_empty());
: 0),
(data.has_base_lang_pack_version()
? data.vbase_lang_pack_version.v
: 0));
Core::App().configUpdated(); Core::App().configUpdated();
if (data.has_autoupdate_url_prefix()) { if (const auto prefix = data.vautoupdate_url_prefix()) {
Local::writeAutoupdatePrefix(qs(data.vautoupdate_url_prefix)); Local::writeAutoupdatePrefix(qs(*prefix));
} }
Local::writeSettings(); Local::writeSettings();
_configExpiresAt = crl::now() _configExpiresAt = crl::now()
+ (data.vexpires.v - unixtime()) * crl::time(1000); + (data.vexpires().v - unixtime()) * crl::time(1000);
requestConfigIfExpired(); requestConfigIfExpired();
emit _instance->configLoaded(); emit _instance->configLoaded();
@ -1198,7 +1192,7 @@ void Instance::Private::exportDone(const MTPauth_ExportedAuthorization &result,
} }
auto &data = result.c_auth_exportedAuthorization(); auto &data = result.c_auth_exportedAuthorization();
_instance->send(MTPauth_ImportAuthorization(data.vid, data.vbytes), rpcDone([this](const MTPauth_Authorization &result, mtpRequestId requestId) { _instance->send(MTPauth_ImportAuthorization(data.vid(), data.vbytes()), rpcDone([this](const MTPauth_Authorization &result, mtpRequestId requestId) {
importDone(result, requestId); importDone(result, requestId);
}), rpcFail([this](const RPCError &error, mtpRequestId requestId) { }), rpcFail([this](const RPCError &error, mtpRequestId requestId) {
return importFail(error, requestId); return importFail(error, requestId);

View file

@ -8,8 +8,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/rpc_sender.h" #include "mtproto/rpc_sender.h"
RPCError::RPCError(const MTPrpcError &error) RPCError::RPCError(const MTPrpcError &error)
: _code(error.c_rpc_error().verror_code.v) { : _code(error.c_rpc_error().verror_code().v) {
QString text = qs(error.c_rpc_error().verror_message); QString text = qs(error.c_rpc_error().verror_message());
if (_code < 0 || _code >= 500) { if (_code < 0 || _code >= 500) {
_type = qsl("INTERNAL_SERVER_ERROR"); _type = qsl("INTERNAL_SERVER_ERROR");
_description = text; _description = text;

View file

@ -380,24 +380,24 @@ void SpecialConfigRequest::handleResponse(const QByteArray &bytes) {
Assert(_simpleConfig.type() == mtpc_help_configSimple); Assert(_simpleConfig.type() == mtpc_help_configSimple);
auto &config = _simpleConfig.c_help_configSimple(); auto &config = _simpleConfig.c_help_configSimple();
auto now = unixtime(); auto now = unixtime();
if (now < config.vdate.v || now > config.vexpires.v) { if (now < config.vdate().v || now > config.vexpires().v) {
LOG(("Config Error: Bad date frame for simple config: %1-%2, our time is %3.").arg(config.vdate.v).arg(config.vexpires.v).arg(now)); LOG(("Config Error: Bad date frame for simple config: %1-%2, our time is %3.").arg(config.vdate().v).arg(config.vexpires().v).arg(now));
return; return;
} }
if (config.vrules.v.empty()) { if (config.vrules().v.empty()) {
LOG(("Config Error: Empty simple config received.")); LOG(("Config Error: Empty simple config received."));
return; return;
} }
for (auto &rule : config.vrules.v) { for (auto &rule : config.vrules().v) {
Assert(rule.type() == mtpc_accessPointRule); Assert(rule.type() == mtpc_accessPointRule);
auto &data = rule.c_accessPointRule(); auto &data = rule.c_accessPointRule();
const auto phoneRules = qs(data.vphone_prefix_rules); const auto phoneRules = qs(data.vphone_prefix_rules());
if (!CheckPhoneByPrefixesRules(_phone, phoneRules)) { if (!CheckPhoneByPrefixesRules(_phone, phoneRules)) {
continue; continue;
} }
const auto dcId = data.vdc_id.v; const auto dcId = data.vdc_id().v;
for (const auto &address : data.vips.v) { for (const auto &address : data.vips().v) {
const auto parseIp = [](const MTPint &ipv4) { const auto parseIp = [](const MTPint &ipv4) {
const auto ip = *reinterpret_cast<const uint32*>(&ipv4.v); const auto ip = *reinterpret_cast<const uint32*>(&ipv4.v);
return qsl("%1.%2.%3.%4" return qsl("%1.%2.%3.%4"
@ -409,15 +409,15 @@ void SpecialConfigRequest::handleResponse(const QByteArray &bytes) {
switch (address.type()) { switch (address.type()) {
case mtpc_ipPort: { case mtpc_ipPort: {
const auto &fields = address.c_ipPort(); const auto &fields = address.c_ipPort();
_callback(dcId, parseIp(fields.vipv4), fields.vport.v, {}); _callback(dcId, parseIp(fields.vipv4()), fields.vport().v, {});
} break; } break;
case mtpc_ipPortSecret: { case mtpc_ipPortSecret: {
const auto &fields = address.c_ipPortSecret(); const auto &fields = address.c_ipPortSecret();
_callback( _callback(
dcId, dcId,
parseIp(fields.vipv4), parseIp(fields.vipv4()),
fields.vport.v, fields.vport().v,
bytes::make_span(fields.vsecret.v)); bytes::make_span(fields.vsecret().v));
} break; } break;
default: Unexpected("Type in simpleConfig ips."); default: Unexpected("Type in simpleConfig ips.");
} }

View file

@ -1,10 +0,0 @@
/*
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 "mtproto/type_utils.h"
const MTPVector<MTPMessageEntity> MTPnullEntities = MTP_vector<MTPMessageEntity>(0);

View file

@ -136,5 +136,3 @@ enum class MTPDchannel_ClientFlag : uint32 {
MIN_FIELD = (1U << 31), MIN_FIELD = (1U << 31),
}; };
DEFINE_MTP_CLIENT_FLAGS(MTPDchannel) DEFINE_MTP_CLIENT_FLAGS(MTPDchannel)
extern const MTPVector<MTPMessageEntity> MTPnullEntities;

View file

@ -143,14 +143,14 @@ void CollectToRequestedRow(
RequestedRow &row, RequestedRow &row,
const MTPSecureRequiredType &data) { const MTPSecureRequiredType &data) {
data.match([&](const MTPDsecureRequiredType &data) { data.match([&](const MTPDsecureRequiredType &data) {
row.values.emplace_back(ConvertType(data.vtype)); row.values.emplace_back(ConvertType(data.vtype()));
auto &value = row.values.back(); auto &value = row.values.back();
value.selfieRequired = data.is_selfie_required(); value.selfieRequired = data.is_selfie_required();
value.translationRequired = data.is_translation_required(); value.translationRequired = data.is_translation_required();
value.nativeNames = data.is_native_names(); value.nativeNames = data.is_native_names();
}, [&](const MTPDsecureRequiredTypeOneOf &data) { }, [&](const MTPDsecureRequiredTypeOneOf &data) {
row.values.reserve(row.values.size() + data.vtypes.v.size()); row.values.reserve(row.values.size() + data.vtypes().v.size());
for (const auto &one : data.vtypes.v) { for (const auto &one : data.vtypes().v) {
CollectToRequestedRow(row, one); CollectToRequestedRow(row, one);
} }
}); });
@ -239,10 +239,10 @@ Config &ConfigInstance() {
Config ParseConfig(const MTPhelp_PassportConfig &data) { Config ParseConfig(const MTPhelp_PassportConfig &data) {
return data.match([](const MTPDhelp_passportConfig &data) { return data.match([](const MTPDhelp_passportConfig &data) {
auto result = Config(); auto result = Config();
result.hash = data.vhash.v; result.hash = data.vhash().v;
auto error = QJsonParseError{ 0, QJsonParseError::NoError }; auto error = QJsonParseError{ 0, QJsonParseError::NoError };
const auto document = QJsonDocument::fromJson( const auto document = QJsonDocument::fromJson(
data.vcountries_langs.c_dataJSON().vdata.v, data.vcountries_langs().c_dataJSON().vdata().v,
&error); &error);
if (error.error != QJsonParseError::NoError) { if (error.error != QJsonParseError::NoError) {
LOG(("API Error: Failed to parse passport config, error: %1." LOG(("API Error: Failed to parse passport config, error: %1."
@ -843,12 +843,11 @@ void FormController::submitPassword(
_passwordCheckRequestId = 0; _passwordCheckRequestId = 0;
_savedPasswordValue = QByteArray(); _savedPasswordValue = QByteArray();
const auto &data = result.c_account_passwordSettings(); const auto &data = result.c_account_passwordSettings();
_password.confirmedEmail = qs(data.vemail); _password.confirmedEmail = qs(data.vemail().value_or_empty());
if (data.has_secure_settings()) { if (const auto wrapped = data.vsecure_settings()) {
const auto &wrapped = data.vsecure_settings; const auto &settings = wrapped->c_secureSecretSettings();
const auto &settings = wrapped.c_secureSecretSettings();
const auto algo = Core::ParseSecureSecretAlgo( const auto algo = Core::ParseSecureSecretAlgo(
settings.vsecure_algo); settings.vsecure_algo());
if (!algo) { if (!algo) {
_view->showUpdateAppBox(); _view->showUpdateAppBox();
return; return;
@ -857,10 +856,10 @@ void FormController::submitPassword(
algo, algo,
bytes::make_span(password)); bytes::make_span(password));
validateSecureSecret( validateSecureSecret(
bytes::make_span(settings.vsecure_secret.v), bytes::make_span(settings.vsecure_secret().v),
hashForSecret, hashForSecret,
bytes::make_span(password), bytes::make_span(password),
settings.vsecure_secret_id.v); settings.vsecure_secret_id().v);
if (!_secret.empty()) { if (!_secret.empty()) {
auto saved = SavedCredentials(); auto saved = SavedCredentials();
saved.hashForAuth = base::take(_passwordCheckHash); saved.hashForAuth = base::take(_passwordCheckHash);
@ -935,22 +934,21 @@ void FormController::checkSavedPasswordSettings(
_passwordCheckRequestId = 0; _passwordCheckRequestId = 0;
const auto &data = result.c_account_passwordSettings(); const auto &data = result.c_account_passwordSettings();
if (data.has_secure_settings()) { if (const auto wrapped = data.vsecure_settings()) {
const auto &wrapped = data.vsecure_settings; const auto &settings = wrapped->c_secureSecretSettings();
const auto &settings = wrapped.c_secureSecretSettings();
const auto algo = Core::ParseSecureSecretAlgo( const auto algo = Core::ParseSecureSecretAlgo(
settings.vsecure_algo); settings.vsecure_algo());
if (!algo) { if (!algo) {
_view->showUpdateAppBox(); _view->showUpdateAppBox();
return; return;
} else if (!settings.vsecure_secret.v.isEmpty() } else if (!settings.vsecure_secret().v.isEmpty()
&& settings.vsecure_secret_id.v == credentials.secretId) { && settings.vsecure_secret_id().v == credentials.secretId) {
_password.confirmedEmail = qs(data.vemail); _password.confirmedEmail = qs(data.vemail().value_or_empty());
validateSecureSecret( validateSecureSecret(
bytes::make_span(settings.vsecure_secret.v), bytes::make_span(settings.vsecure_secret().v),
credentials.hashForSecret, credentials.hashForSecret,
{}, {},
settings.vsecure_secret_id.v); settings.vsecure_secret_id().v);
} }
} }
if (_secret.empty()) { if (_secret.empty()) {
@ -982,7 +980,7 @@ void FormController::recoverPassword() {
_recoverRequestId = 0; _recoverRequestId = 0;
const auto &data = result.c_auth_passwordRecovery(); const auto &data = result.c_auth_passwordRecovery();
const auto pattern = qs(data.vemail_pattern); const auto pattern = qs(data.vemail_pattern());
const auto box = _view->show(Box<RecoverBox>( const auto box = _view->show(Box<RecoverBox>(
pattern, pattern,
_password.notEmptyPassport)); _password.notEmptyPassport));
@ -1096,7 +1094,7 @@ void FormController::resetSecret(
MTPstring(), // email MTPstring(), // email
MTP_secureSecretSettings( MTP_secureSecretSettings(
MTP_securePasswordKdfAlgoUnknown(), // secure_algo MTP_securePasswordKdfAlgoUnknown(), // secure_algo
MTP_bytes(QByteArray()), // secure_secret MTP_bytes(), // secure_secret
MTP_long(0))) // secure_secret_id MTP_long(0))) // secure_secret_id
)).done([=](const MTPBool &result) { )).done([=](const MTPBool &result) {
_saveSecretRequestId = 0; _saveSecretRequestId = 0;
@ -1145,11 +1143,11 @@ void FormController::fillErrors() {
return nullptr; return nullptr;
}; };
const auto setSpecialScanError = [&](FileType type, auto &&data) { const auto setSpecialScanError = [&](FileType type, auto &&data) {
if (const auto value = find(data.vtype)) { if (const auto value = find(data.vtype())) {
if (value->requiresSpecialScan(type)) { if (value->requiresSpecialScan(type)) {
const auto i = value->specialScans.find(type); const auto i = value->specialScans.find(type);
if (i != value->specialScans.end()) { if (i != value->specialScans.end()) {
i->second.error = qs(data.vtext); i->second.error = qs(data.vtext());
} else { } else {
LOG(("API Error: " LOG(("API Error: "
"Special scan %1 not found for error value." "Special scan %1 not found for error value."
@ -1160,48 +1158,48 @@ void FormController::fillErrors() {
}; };
for (const auto &error : _form.pendingErrors) { for (const auto &error : _form.pendingErrors) {
error.match([&](const MTPDsecureValueError &data) { error.match([&](const MTPDsecureValueError &data) {
if (const auto value = find(data.vtype)) { if (const auto value = find(data.vtype())) {
if (CanHaveErrors(value->type)) { if (CanHaveErrors(value->type)) {
value->error = qs(data.vtext); value->error = qs(data.vtext());
} }
} }
}, [&](const MTPDsecureValueErrorData &data) { }, [&](const MTPDsecureValueErrorData &data) {
if (const auto value = find(data.vtype)) { if (const auto value = find(data.vtype())) {
const auto key = qs(data.vfield); const auto key = qs(data.vfield());
if (CanHaveErrors(value->type) if (CanHaveErrors(value->type)
&& !SkipFieldCheck(value, key)) { && !SkipFieldCheck(value, key)) {
value->data.parsed.fields[key].error = qs(data.vtext); value->data.parsed.fields[key].error = qs(data.vtext());
} }
} }
}, [&](const MTPDsecureValueErrorFile &data) { }, [&](const MTPDsecureValueErrorFile &data) {
const auto hash = bytes::make_span(data.vfile_hash.v); const auto hash = bytes::make_span(data.vfile_hash().v);
if (const auto value = find(data.vtype)) { if (const auto value = find(data.vtype())) {
if (const auto file = scan(*value, FileType::Scan, hash)) { if (const auto file = scan(*value, FileType::Scan, hash)) {
if (value->requiresScan(FileType::Scan)) { if (value->requiresScan(FileType::Scan)) {
file->error = qs(data.vtext); file->error = qs(data.vtext());
} }
} }
} }
}, [&](const MTPDsecureValueErrorFiles &data) { }, [&](const MTPDsecureValueErrorFiles &data) {
if (const auto value = find(data.vtype)) { if (const auto value = find(data.vtype())) {
if (value->requiresScan(FileType::Scan)) { if (value->requiresScan(FileType::Scan)) {
value->fileMissingError(FileType::Scan) value->fileMissingError(FileType::Scan)
= qs(data.vtext); = qs(data.vtext());
} }
} }
}, [&](const MTPDsecureValueErrorTranslationFile &data) { }, [&](const MTPDsecureValueErrorTranslationFile &data) {
const auto hash = bytes::make_span(data.vfile_hash.v); const auto hash = bytes::make_span(data.vfile_hash().v);
if (const auto value = find(data.vtype)) { if (const auto value = find(data.vtype())) {
const auto file = scan(*value, FileType::Translation, hash); const auto file = scan(*value, FileType::Translation, hash);
if (file && value->requiresScan(FileType::Translation)) { if (file && value->requiresScan(FileType::Translation)) {
file->error = qs(data.vtext); file->error = qs(data.vtext());
} }
} }
}, [&](const MTPDsecureValueErrorTranslationFiles &data) { }, [&](const MTPDsecureValueErrorTranslationFiles &data) {
if (const auto value = find(data.vtype)) { if (const auto value = find(data.vtype())) {
if (value->requiresScan(FileType::Translation)) { if (value->requiresScan(FileType::Translation)) {
value->fileMissingError(FileType::Translation) value->fileMissingError(FileType::Translation)
= qs(data.vtext); = qs(data.vtext());
} }
} }
}, [&](const MTPDsecureValueErrorFrontSide &data) { }, [&](const MTPDsecureValueErrorFrontSide &data) {
@ -2094,8 +2092,8 @@ void FormController::startPhoneVerification(not_null<Value*> value) {
value->verification.requestId = 0; value->verification.requestId = 0;
const auto &data = result.c_auth_sentCode(); const auto &data = result.c_auth_sentCode();
value->verification.phoneCodeHash = qs(data.vphone_code_hash); value->verification.phoneCodeHash = qs(data.vphone_code_hash());
switch (data.vtype.type()) { switch (data.vtype().type()) {
case mtpc_auth_sentCodeTypeApp: case mtpc_auth_sentCodeTypeApp:
LOG(("API Error: sentCodeTypeApp not expected " LOG(("API Error: sentCodeTypeApp not expected "
"in FormController::startPhoneVerification.")); "in FormController::startPhoneVerification."));
@ -2105,33 +2103,32 @@ void FormController::startPhoneVerification(not_null<Value*> value) {
"in FormController::startPhoneVerification.")); "in FormController::startPhoneVerification."));
return; return;
case mtpc_auth_sentCodeTypeCall: { case mtpc_auth_sentCodeTypeCall: {
const auto &type = data.vtype.c_auth_sentCodeTypeCall(); const auto &type = data.vtype().c_auth_sentCodeTypeCall();
value->verification.codeLength = (type.vlength.v > 0) value->verification.codeLength = (type.vlength().v > 0)
? type.vlength.v ? type.vlength().v
: -1; : -1;
value->verification.call = std::make_unique<SentCodeCall>( value->verification.call = std::make_unique<SentCodeCall>(
[=] { requestPhoneCall(value); }, [=] { requestPhoneCall(value); },
[=] { _verificationUpdate.fire_copy(value); }); [=] { _verificationUpdate.fire_copy(value); });
value->verification.call->setStatus( value->verification.call->setStatus(
{ SentCodeCall::State::Called, 0 }); { SentCodeCall::State::Called, 0 });
if (data.has_next_type()) { if (data.vnext_type()) {
LOG(("API Error: next_type is not supported for calls.")); LOG(("API Error: next_type is not supported for calls."));
} }
} break; } break;
case mtpc_auth_sentCodeTypeSms: { case mtpc_auth_sentCodeTypeSms: {
const auto &type = data.vtype.c_auth_sentCodeTypeSms(); const auto &type = data.vtype().c_auth_sentCodeTypeSms();
value->verification.codeLength = (type.vlength.v > 0) value->verification.codeLength = (type.vlength().v > 0)
? type.vlength.v ? type.vlength().v
: -1; : -1;
const auto &next = data.vnext_type; const auto next = data.vnext_type();
if (data.has_next_type() if (next && next->type() == mtpc_auth_codeTypeCall) {
&& next.type() == mtpc_auth_codeTypeCall) {
value->verification.call = std::make_unique<SentCodeCall>( value->verification.call = std::make_unique<SentCodeCall>(
[=] { requestPhoneCall(value); }, [=] { requestPhoneCall(value); },
[=] { _verificationUpdate.fire_copy(value); }); [=] { _verificationUpdate.fire_copy(value); });
value->verification.call->setStatus({ value->verification.call->setStatus({
SentCodeCall::State::Waiting, SentCodeCall::State::Waiting,
data.has_timeout() ? data.vtimeout.v : 60 }); data.vtimeout().value_or(60) });
} }
} break; } break;
} }
@ -2150,8 +2147,8 @@ void FormController::startEmailVerification(not_null<Value*> value) {
value->verification.requestId = 0; value->verification.requestId = 0;
const auto &data = result.c_account_sentEmailCode(); const auto &data = result.c_account_sentEmailCode();
value->verification.codeLength = (data.vlength.v > 0) value->verification.codeLength = (data.vlength().v > 0)
? data.vlength.v ? data.vlength().v
: -1; : -1;
_verificationNeeded.fire_copy(value); _verificationNeeded.fire_copy(value);
}).fail([=](const RPCError &error) { }).fail([=](const RPCError &error) {
@ -2303,13 +2300,13 @@ auto FormController::parseFile(
case mtpc_secureFile: { case mtpc_secureFile: {
const auto &fields = data.c_secureFile(); const auto &fields = data.c_secureFile();
auto result = File(); auto result = File();
result.id = fields.vid.v; result.id = fields.vid().v;
result.accessHash = fields.vaccess_hash.v; result.accessHash = fields.vaccess_hash().v;
result.size = fields.vsize.v; result.size = fields.vsize().v;
result.date = fields.vdate.v; result.date = fields.vdate().v;
result.dcId = fields.vdc_id.v; result.dcId = fields.vdc_id().v;
result.hash = bytes::make_vector(fields.vfile_hash.v); result.hash = bytes::make_vector(fields.vfile_hash().v);
result.encryptedSecret = bytes::make_vector(fields.vsecret.v); result.encryptedSecret = bytes::make_vector(fields.vsecret().v);
fillDownloadedFile(result, editData); fillDownloadedFile(result, editData);
return result; return result;
} break; } break;
@ -2351,22 +2348,22 @@ auto FormController::parseValue(
Expects(value.type() == mtpc_secureValue); Expects(value.type() == mtpc_secureValue);
const auto &data = value.c_secureValue(); const auto &data = value.c_secureValue();
const auto type = ConvertType(data.vtype); const auto type = ConvertType(data.vtype());
auto result = Value(type); auto result = Value(type);
result.submitHash = bytes::make_vector(data.vhash.v); result.submitHash = bytes::make_vector(data.vhash().v);
if (data.has_data()) { if (const auto secureData = data.vdata()) {
Assert(data.vdata.type() == mtpc_secureData); secureData->match([&](const MTPDsecureData &data) {
const auto &fields = data.vdata.c_secureData(); result.data.original = data.vdata().v;
result.data.original = fields.vdata.v; result.data.hash = bytes::make_vector(data.vdata_hash().v);
result.data.hash = bytes::make_vector(fields.vdata_hash.v); result.data.encryptedSecret = bytes::make_vector(data.vsecret().v);
result.data.encryptedSecret = bytes::make_vector(fields.vsecret.v); });
} }
if (data.has_files()) { if (const auto files = data.vfiles()) {
result.files(FileType::Scan) = parseFiles(data.vfiles.v, editData); result.files(FileType::Scan) = parseFiles(files->v, editData);
} }
if (data.has_translation()) { if (const auto translation = data.vtranslation()) {
result.files(FileType::Translation) = parseFiles( result.files(FileType::Translation) = parseFiles(
data.vtranslation.v, translation->v,
editData); editData);
} }
const auto parseSpecialScan = [&]( const auto parseSpecialScan = [&](
@ -2376,26 +2373,21 @@ auto FormController::parseValue(
result.specialScans.emplace(type, std::move(*parsed)); result.specialScans.emplace(type, std::move(*parsed));
} }
}; };
if (data.has_front_side()) { if (const auto side = data.vfront_side()) {
parseSpecialScan(FileType::FrontSide, data.vfront_side); parseSpecialScan(FileType::FrontSide, *side);
} }
if (data.has_reverse_side()) { if (const auto side = data.vreverse_side()) {
parseSpecialScan(FileType::ReverseSide, data.vreverse_side); parseSpecialScan(FileType::ReverseSide, *side);
} }
if (data.has_selfie()) { if (const auto selfie = data.vselfie()) {
parseSpecialScan(FileType::Selfie, data.vselfie); parseSpecialScan(FileType::Selfie, *selfie);
} }
if (data.has_plain_data()) { if (const auto plain = data.vplain_data()) {
switch (data.vplain_data.type()) { plain->match([&](const MTPDsecurePlainPhone &data) {
case mtpc_securePlainPhone: { result.data.parsed.fields["value"].text = qs(data.vphone());
const auto &fields = data.vplain_data.c_securePlainPhone(); }, [&](const MTPDsecurePlainEmail &data) {
result.data.parsed.fields["value"].text = qs(fields.vphone); result.data.parsed.fields["value"].text = qs(data.vemail());
} break; });
case mtpc_securePlainEmail: {
const auto &fields = data.vplain_data.c_securePlainEmail();
result.data.parsed.fields["value"].text = qs(fields.vemail);
} break;
}
} }
return result; return result;
} }
@ -2494,9 +2486,9 @@ bool FormController::parseForm(const MTPaccount_AuthorizationForm &result) {
const auto &data = result.c_account_authorizationForm(); const auto &data = result.c_account_authorizationForm();
Auth().data().processUsers(data.vusers); Auth().data().processUsers(data.vusers());
for (const auto &value : data.vvalues.v) { for (const auto &value : data.vvalues().v) {
auto parsed = parseValue(value); auto parsed = parseValue(value);
const auto type = parsed.type; const auto type = parsed.type;
const auto alreadyIt = _form.values.find(type); const auto alreadyIt = _form.values.find(type);
@ -2507,10 +2499,10 @@ bool FormController::parseForm(const MTPaccount_AuthorizationForm &result) {
} }
_form.values.emplace(type, std::move(parsed)); _form.values.emplace(type, std::move(parsed));
} }
if (data.has_privacy_policy_url()) { if (const auto url = data.vprivacy_policy_url()) {
_form.privacyPolicyUrl = qs(data.vprivacy_policy_url); _form.privacyPolicyUrl = qs(*url);
} }
for (const auto &required : data.vrequired_types.v) { for (const auto &required : data.vrequired_types().v) {
const auto row = CollectRequestedRow(required); const auto row = CollectRequestedRow(required);
for (const auto requested : row.values) { for (const auto requested : row.values) {
const auto type = requested.type; const auto type = requested.type;
@ -2529,7 +2521,7 @@ bool FormController::parseForm(const MTPaccount_AuthorizationForm &result) {
return false; return false;
} }
_bot = Auth().data().userLoaded(_request.botId); _bot = Auth().data().userLoaded(_request.botId);
_form.pendingErrors = data.verrors.v; _form.pendingErrors = data.verrors().v;
return true; return true;
} }
@ -2608,20 +2600,18 @@ void FormController::showForm() {
bool FormController::applyPassword(const MTPDaccount_password &result) { bool FormController::applyPassword(const MTPDaccount_password &result) {
auto settings = PasswordSettings(); auto settings = PasswordSettings();
settings.hint = qs(result.vhint); settings.hint = qs(result.vhint().value_or_empty());
settings.hasRecovery = result.is_has_recovery(); settings.hasRecovery = result.is_has_recovery();
settings.notEmptyPassport = result.is_has_secure_values(); settings.notEmptyPassport = result.is_has_secure_values();
settings.request = Core::ParseCloudPasswordCheckRequest(result); settings.request = Core::ParseCloudPasswordCheckRequest(result);
settings.unknownAlgo = result.has_current_algo() settings.unknownAlgo = result.vcurrent_algo() && !settings.request;
&& !settings.request; settings.unconfirmedPattern =
settings.unconfirmedPattern = result.has_email_unconfirmed_pattern() qs(result.vemail_unconfirmed_pattern().value_or_empty());
? qs(result.vemail_unconfirmed_pattern)
: QString();
settings.newAlgo = Core::ValidateNewCloudPasswordAlgo( settings.newAlgo = Core::ValidateNewCloudPasswordAlgo(
Core::ParseCloudPasswordAlgo(result.vnew_algo)); Core::ParseCloudPasswordAlgo(result.vnew_algo()));
settings.newSecureAlgo = Core::ValidateNewSecureSecretAlgo( settings.newSecureAlgo = Core::ValidateNewSecureSecretAlgo(
Core::ParseSecureSecretAlgo(result.vnew_secure_algo)); Core::ParseSecureSecretAlgo(result.vnew_secure_algo()));
openssl::AddRandomSeed(bytes::make_span(result.vsecure_random.v)); openssl::AddRandomSeed(bytes::make_span(result.vsecure_random().v));
return applyPassword(std::move(settings)); return applyPassword(std::move(settings));
} }

View file

@ -137,7 +137,7 @@ AdminLog::OwnedItem GenerateForwardedItem(
MTP_string(text), MTP_string(text),
MTPMessageMedia(), MTPMessageMedia(),
MTPReplyMarkup(), MTPReplyMarkup(),
MTPnullEntities, MTPVector<MTPMessageEntity>(),
MTPint(), // views MTPint(), // views
MTPint(), // edit_date MTPint(), // edit_date
MTPstring(), // post_author MTPstring(), // post_author
@ -193,8 +193,8 @@ void BlockedBoxController::loadMoreRows() {
_loadRequestId = 0; _loadRequestId = 0;
auto handleContactsBlocked = [](auto &list) { auto handleContactsBlocked = [](auto &list) {
Auth().data().processUsers(list.vusers); Auth().data().processUsers(list.vusers());
return list.vblocked.v; return list.vblocked().v;
}; };
switch (result.type()) { switch (result.type()) {
case mtpc_contacts_blockedSlice: { case mtpc_contacts_blockedSlice: {
@ -232,7 +232,7 @@ void BlockedBoxController::receivedUsers(const QVector<MTPContactBlocked> &resul
_offset += result.size(); _offset += result.size();
for (const auto &item : result) { for (const auto &item : result) {
item.match([&](const MTPDcontactBlocked &data) { item.match([&](const MTPDcontactBlocked &data) {
if (const auto user = Auth().data().userLoaded(data.vuser_id.v)) { if (const auto user = Auth().data().userLoaded(data.vuser_id().v)) {
appendRow(user); appendRow(user);
user->setIsBlocked(true); user->setIsBlocked(true);
} }

View file

@ -836,7 +836,7 @@ void mtpFileLoader::normalPartLoaded(
if (result.type() == mtpc_upload_fileCdnRedirect) { if (result.type() == mtpc_upload_fileCdnRedirect) {
return switchToCDN(offset, result.c_upload_fileCdnRedirect()); return switchToCDN(offset, result.c_upload_fileCdnRedirect());
} }
auto buffer = bytes::make_span(result.c_upload_file().vbytes.v); auto buffer = bytes::make_span(result.c_upload_file().vbytes().v);
return partLoaded(offset, buffer); return partLoaded(offset, buffer);
} }
@ -846,16 +846,16 @@ void mtpFileLoader::webPartLoaded(
result.match([&](const MTPDupload_webFile &data) { result.match([&](const MTPDupload_webFile &data) {
const auto offset = finishSentRequestGetOffset(requestId); const auto offset = finishSentRequestGetOffset(requestId);
if (!_size) { if (!_size) {
_size = data.vsize.v; _size = data.vsize().v;
} else if (data.vsize.v != _size) { } else if (data.vsize().v != _size) {
LOG(("MTP Error: " LOG(("MTP Error: "
"Bad size provided by bot for webDocument: %1, real: %2" "Bad size provided by bot for webDocument: %1, real: %2"
).arg(_size ).arg(_size
).arg(data.vsize.v)); ).arg(data.vsize().v));
cancel(true); cancel(true);
return; return;
} }
partLoaded(offset, bytes::make_span(data.vbytes.v)); partLoaded(offset, bytes::make_span(data.vbytes().v));
}); });
} }
@ -874,7 +874,7 @@ void mtpFileLoader::cdnPartLoaded(const MTPupload_CdnFile &result, mtpRequestId
const auto requestId = MTP::send( const auto requestId = MTP::send(
MTPupload_ReuploadCdnFile( MTPupload_ReuploadCdnFile(
MTP_bytes(_cdnToken), MTP_bytes(_cdnToken),
data.vrequest_token), data.vrequest_token()),
rpcDone(&mtpFileLoader::reuploadDone), rpcDone(&mtpFileLoader::reuploadDone),
rpcFail(&mtpFileLoader::cdnPartFailed), rpcFail(&mtpFileLoader::cdnPartFailed),
shiftedDcId); shiftedDcId);
@ -895,7 +895,7 @@ void mtpFileLoader::cdnPartLoaded(const MTPupload_CdnFile &result, mtpRequestId
state.ivec[13] = static_cast<uchar>((counterOffset >> 16) & 0xFF); state.ivec[13] = static_cast<uchar>((counterOffset >> 16) & 0xFF);
state.ivec[12] = static_cast<uchar>((counterOffset >> 24) & 0xFF); state.ivec[12] = static_cast<uchar>((counterOffset >> 24) & 0xFF);
auto decryptInPlace = data.vbytes.v; auto decryptInPlace = data.vbytes().v;
auto buffer = bytes::make_detached_span(decryptInPlace); auto buffer = bytes::make_detached_span(decryptInPlace);
MTP::aesCtrEncrypt(buffer, key.data(), &state); MTP::aesCtrEncrypt(buffer, key.data(), &state);
@ -1119,19 +1119,19 @@ void mtpFileLoader::switchToCDN(
const MTPDupload_fileCdnRedirect &redirect) { const MTPDupload_fileCdnRedirect &redirect) {
changeCDNParams( changeCDNParams(
offset, offset,
redirect.vdc_id.v, redirect.vdc_id().v,
redirect.vfile_token.v, redirect.vfile_token().v,
redirect.vencryption_key.v, redirect.vencryption_key().v,
redirect.vencryption_iv.v, redirect.vencryption_iv().v,
redirect.vfile_hashes.v); redirect.vfile_hashes().v);
} }
void mtpFileLoader::addCdnHashes(const QVector<MTPFileHash> &hashes) { void mtpFileLoader::addCdnHashes(const QVector<MTPFileHash> &hashes) {
for (const auto &hash : hashes) { for (const auto &hash : hashes) {
hash.match([&](const MTPDfileHash &data) { hash.match([&](const MTPDfileHash &data) {
_cdnFileHashes.emplace( _cdnFileHashes.emplace(
data.voffset.v, data.voffset().v,
CdnFileHash{ data.vlimit.v, data.vhash.v }); CdnFileHash{ data.vlimit().v, data.vhash().v });
}); });
} }
} }

View file

@ -37,7 +37,7 @@ struct PreparedFileThumbnail {
QString name; QString name;
QImage image; QImage image;
QByteArray bytes; QByteArray bytes;
MTPPhotoSize mtpSize = MTP_photoSizeEmpty(MTP_string("")); MTPPhotoSize mtpSize = MTP_photoSizeEmpty(MTP_string());
}; };
PreparedFileThumbnail PrepareFileThumbnail(QImage &&original) { PreparedFileThumbnail PrepareFileThumbnail(QImage &&original) {
@ -67,7 +67,7 @@ PreparedFileThumbnail PrepareFileThumbnail(QImage &&original) {
Qt::SmoothTransformation) Qt::SmoothTransformation)
: std::move(original); : std::move(original);
result.mtpSize = MTP_photoSize( result.mtpSize = MTP_photoSize(
MTP_string(""), MTP_string(),
MTP_fileLocationToBeDeprecated(MTP_long(0), MTP_int(0)), MTP_fileLocationToBeDeprecated(MTP_long(0), MTP_int(0)),
MTP_int(result.image.width()), MTP_int(result.image.width()),
MTP_int(result.image.height()), MTP_int(result.image.height()),
@ -216,7 +216,7 @@ SendMediaReady PreparePeerPhoto(PeerId peerId, QImage &&image) {
MTP_flags(0), MTP_flags(0),
MTP_long(id), MTP_long(id),
MTP_long(0), MTP_long(0),
MTP_bytes(QByteArray()), MTP_bytes(),
MTP_int(unixtime()), MTP_int(unixtime()),
MTP_vector<MTPPhotoSize>(photoSizes), MTP_vector<MTPPhotoSize>(photoSizes),
MTP_int(MTP::maindc())); MTP_int(MTP::maindc()));
@ -279,7 +279,7 @@ SendMediaReady PrepareWallPaper(const QImage &image) {
MTP_flags(0), MTP_flags(0),
MTP_long(id), MTP_long(id),
MTP_long(0), MTP_long(0),
MTP_bytes(QByteArray()), MTP_bytes(),
MTP_int(unixtime()), MTP_int(unixtime()),
MTP_string("image/jpeg"), MTP_string("image/jpeg"),
MTP_int(jpeg.size()), MTP_int(jpeg.size()),
@ -471,7 +471,10 @@ void SendingAlbum::refreshMediaCaption(not_null<HistoryItem*> item) {
return; return;
} }
i->media = i->media->match([&](const MTPDinputSingleMedia &data) { i->media = i->media->match([&](const MTPDinputSingleMedia &data) {
return PrepareAlbumItemMedia(item, data.vmedia, data.vrandom_id.v); return PrepareAlbumItemMedia(
item,
data.vmedia(),
data.vrandom_id().v);
}); });
} }
@ -891,7 +894,7 @@ void FileLoadTask::process() {
if (isSticker) { if (isSticker) {
attributes.push_back(MTP_documentAttributeSticker( attributes.push_back(MTP_documentAttributeSticker(
MTP_flags(0), MTP_flags(0),
MTP_string(QString()), MTP_string(),
MTP_inputStickerSetEmpty(), MTP_inputStickerSetEmpty(),
MTPMaskCoords())); MTPMaskCoords()));
if (isAnimation) { if (isAnimation) {
@ -925,7 +928,7 @@ void FileLoadTask::process() {
MTP_flags(0), MTP_flags(0),
MTP_long(_id), MTP_long(_id),
MTP_long(0), MTP_long(0),
MTP_bytes(QByteArray()), MTP_bytes(),
MTP_int(unixtime()), MTP_int(unixtime()),
MTP_vector<MTPPhotoSize>(photoSizes), MTP_vector<MTPPhotoSize>(photoSizes),
MTP_int(MTP::maindc())); MTP_int(MTP::maindc()));
@ -955,7 +958,7 @@ void FileLoadTask::process() {
MTP_flags(0), MTP_flags(0),
MTP_long(_id), MTP_long(_id),
MTP_long(0), MTP_long(0),
MTP_bytes(QByteArray()), MTP_bytes(),
MTP_int(unixtime()), MTP_int(unixtime()),
MTP_string(filemime), MTP_string(filemime),
MTP_int(filesize), MTP_int(filesize),
@ -967,7 +970,7 @@ void FileLoadTask::process() {
MTP_flags(0), MTP_flags(0),
MTP_long(_id), MTP_long(_id),
MTP_long(0), MTP_long(0),
MTP_bytes(QByteArray()), MTP_bytes(),
MTP_int(unixtime()), MTP_int(unixtime()),
MTP_string(filemime), MTP_string(filemime),
MTP_int(filesize), MTP_int(filesize),

View file

@ -4667,15 +4667,15 @@ void WriteExportSettings(const Export::Settings &settings) {
settings.singlePeer.match([&](const MTPDinputPeerUser & user) { settings.singlePeer.match([&](const MTPDinputPeerUser & user) {
data.stream data.stream
<< kSinglePeerTypeUser << kSinglePeerTypeUser
<< qint32(user.vuser_id.v) << qint32(user.vuser_id().v)
<< quint64(user.vaccess_hash.v); << quint64(user.vaccess_hash().v);
}, [&](const MTPDinputPeerChat & chat) { }, [&](const MTPDinputPeerChat & chat) {
data.stream << kSinglePeerTypeChat << qint32(chat.vchat_id.v); data.stream << kSinglePeerTypeChat << qint32(chat.vchat_id().v);
}, [&](const MTPDinputPeerChannel & channel) { }, [&](const MTPDinputPeerChannel & channel) {
data.stream data.stream
<< kSinglePeerTypeChannel << kSinglePeerTypeChannel
<< qint32(channel.vchannel_id.v) << qint32(channel.vchannel_id().v)
<< quint64(channel.vaccess_hash.v); << quint64(channel.vaccess_hash().v);
}, [&](const MTPDinputPeerSelf &) { }, [&](const MTPDinputPeerSelf &) {
data.stream << kSinglePeerTypeSelf; data.stream << kSinglePeerTypeSelf;
}, [&](const MTPDinputPeerEmpty &) { }, [&](const MTPDinputPeerEmpty &) {

View file

@ -303,18 +303,18 @@ AdminLog::OwnedItem GenerateContactItem(
MTP_int(viaBotId), MTP_int(viaBotId),
MTP_int(replyTo), MTP_int(replyTo),
MTP_int(unixtime()), MTP_int(unixtime()),
MTP_string(QString()), MTP_string(),
MTP_messageMediaContact( MTP_messageMediaContact(
MTP_string(data.phone), MTP_string(data.phone),
MTP_string(data.firstName), MTP_string(data.firstName),
MTP_string(data.lastName), MTP_string(data.lastName),
MTP_string(QString()), MTP_string(),
MTP_int(0)), MTP_int(0)),
MTPReplyMarkup(), MTPReplyMarkup(),
MTPVector<MTPMessageEntity>(), MTPVector<MTPMessageEntity>(),
MTP_int(0), MTP_int(0),
MTP_int(0), MTP_int(0),
MTP_string(QString()), MTP_string(),
MTP_long(0)); MTP_long(0));
const auto item = history->owner().makeMessage( const auto item = history->owner().makeMessage(
history, history,

View file

@ -280,7 +280,7 @@ Helper::Helper(not_null<AuthSession*> session)
request(MTPhelp_GetSupportName( request(MTPhelp_GetSupportName(
)).done([=](const MTPhelp_SupportName &result) { )).done([=](const MTPhelp_SupportName &result) {
result.match([&](const MTPDhelp_supportName &data) { result.match([&](const MTPDhelp_supportName &data) {
setSupportName(qs(data.vname)); setSupportName(qs(data.vname()));
}); });
}).fail([=](const RPCError &error) { }).fail([=](const RPCError &error) {
setSupportName( setSupportName(
@ -434,11 +434,11 @@ void Helper::applyInfo(
}; };
result.match([&](const MTPDhelp_userInfo &data) { result.match([&](const MTPDhelp_userInfo &data) {
auto info = UserInfo(); auto info = UserInfo();
info.author = qs(data.vauthor); info.author = qs(data.vauthor());
info.date = data.vdate.v; info.date = data.vdate().v;
info.text = TextWithEntities{ info.text = TextWithEntities{
qs(data.vmessage), qs(data.vmessage()),
TextUtilities::EntitiesFromMTP(data.ventities.v) }; TextUtilities::EntitiesFromMTP(data.ventities().v) };
if (info.text.empty()) { if (info.text.empty()) {
remove(); remove();
} else if (_userInformation[user] != info) { } else if (_userInformation[user] != info) {

View file

@ -233,24 +233,24 @@ ImagePtr CreateFromPhotoSize(
const MTPPhotoSize &size, const MTPPhotoSize &size,
Method method = Method()) { Method method = Method()) {
return size.match([&](const MTPDphotoSize &data) { return size.match([&](const MTPDphotoSize &data) {
const auto &location = data.vlocation.c_fileLocationToBeDeprecated(); const auto &location = data.vlocation().c_fileLocationToBeDeprecated();
return method( return method(
StorageImageLocation( StorageImageLocation(
createLocation(data.vtype, location), createLocation(data.vtype(), location),
data.vw.v, data.vw().v,
data.vh.v), data.vh().v),
data.vsize.v); data.vsize().v);
}, [&](const MTPDphotoCachedSize &data) { }, [&](const MTPDphotoCachedSize &data) {
const auto bytes = qba(data.vbytes); const auto bytes = qba(data.vbytes());
const auto &location = data.vlocation.c_fileLocationToBeDeprecated(); const auto &location = data.vlocation().c_fileLocationToBeDeprecated();
return method( return method(
StorageImageLocation( StorageImageLocation(
createLocation(data.vtype, location), createLocation(data.vtype(), location),
data.vw.v, data.vw().v,
data.vh.v), data.vh().v),
bytes); bytes);
}, [&](const MTPDphotoStrippedSize &data) { }, [&](const MTPDphotoStrippedSize &data) {
const auto bytes = qba(data.vbytes); const auto bytes = qba(data.vbytes());
if (bytes.size() < 3 || bytes[0] != '\x01') { if (bytes.size() < 3 || bytes[0] != '\x01') {
return ImagePtr(); return ImagePtr();
} }
@ -307,18 +307,21 @@ ImagePtr CreateFromPhotoSize(
} }
ImagePtr Create(const MTPDstickerSet &set, const MTPPhotoSize &size) { ImagePtr Create(const MTPDstickerSet &set, const MTPPhotoSize &size) {
const auto thumbDcId = set.vthumb_dc_id();
const auto create = [&]( const auto create = [&](
const MTPstring &thumbSize, const MTPstring &thumbSize,
const MTPDfileLocationToBeDeprecated &location) { const MTPDfileLocationToBeDeprecated &location) {
return StorageFileLocation( return StorageFileLocation(
set.vthumb_dc_id.v, thumbDcId->v,
Auth().userId(), Auth().userId(),
MTP_inputStickerSetThumb( MTP_inputStickerSetThumb(
MTP_inputStickerSetID(set.vid, set.vaccess_hash), MTP_inputStickerSetID(set.vid(), set.vaccess_hash()),
location.vvolume_id, location.vvolume_id(),
location.vlocal_id)); location.vlocal_id()));
}; };
return CreateFromPhotoSize(create, size, CreateSetThumbnail()); return thumbDcId
? CreateFromPhotoSize(create, size, CreateSetThumbnail())
: ImagePtr();
} }
ImagePtr CreateStickerSetThumbnail(const StorageImageLocation &location) { ImagePtr CreateStickerSetThumbnail(const StorageImageLocation &location) {
@ -330,12 +333,12 @@ ImagePtr Create(const MTPDphoto &photo, const MTPPhotoSize &size) {
const MTPstring &thumbSize, const MTPstring &thumbSize,
const MTPDfileLocationToBeDeprecated &location) { const MTPDfileLocationToBeDeprecated &location) {
return StorageFileLocation( return StorageFileLocation(
photo.vdc_id.v, photo.vdc_id().v,
Auth().userId(), Auth().userId(),
MTP_inputPhotoFileLocation( MTP_inputPhotoFileLocation(
photo.vid, photo.vid(),
photo.vaccess_hash, photo.vaccess_hash(),
photo.vfile_reference, photo.vfile_reference(),
thumbSize)); thumbSize));
}; };
return CreateFromPhotoSize(create, size); return CreateFromPhotoSize(create, size);
@ -346,12 +349,12 @@ ImagePtr Create(const MTPDdocument &document, const MTPPhotoSize &size) {
const MTPstring &thumbSize, const MTPstring &thumbSize,
const MTPDfileLocationToBeDeprecated &location) { const MTPDfileLocationToBeDeprecated &location) {
return StorageFileLocation( return StorageFileLocation(
document.vdc_id.v, document.vdc_id().v,
Auth().userId(), Auth().userId(),
MTP_inputDocumentFileLocation( MTP_inputDocumentFileLocation(
document.vid, document.vid(),
document.vaccess_hash, document.vaccess_hash(),
document.vfile_reference, document.vfile_reference(),
thumbSize)); thumbSize));
}; };
return CreateFromPhotoSize(create, size); return CreateFromPhotoSize(create, size);
@ -361,63 +364,63 @@ QSize getImageSize(const QVector<MTPDocumentAttribute> &attributes) {
for (const auto &attribute : attributes) { for (const auto &attribute : attributes) {
if (attribute.type() == mtpc_documentAttributeImageSize) { if (attribute.type() == mtpc_documentAttributeImageSize) {
auto &size = attribute.c_documentAttributeImageSize(); auto &size = attribute.c_documentAttributeImageSize();
return QSize(size.vw.v, size.vh.v); return QSize(size.vw().v, size.vh().v);
} }
} }
return QSize(); return QSize();
} }
ImagePtr Create(const MTPDwebDocument &document) { ImagePtr Create(const MTPDwebDocument &document) {
const auto size = getImageSize(document.vattributes.v); const auto size = getImageSize(document.vattributes().v);
if (size.isEmpty()) { if (size.isEmpty()) {
return ImagePtr(); return ImagePtr();
} }
// We don't use size from WebDocument, because it is not reliable. // We don't use size from WebDocument, because it is not reliable.
// It can be > 0 and different from the real size that we get in upload.WebFile result. // It can be > 0 and different from the real size that we get in upload.WebFile result.
auto filesize = 0; // document.vsize.v; auto filesize = 0; // document.vsize().v;
return Create( return Create(
WebFileLocation( WebFileLocation(
document.vurl.v, document.vurl().v,
document.vaccess_hash.v), document.vaccess_hash().v),
size.width(), size.width(),
size.height(), size.height(),
filesize); filesize);
} }
ImagePtr Create(const MTPDwebDocumentNoProxy &document) { ImagePtr Create(const MTPDwebDocumentNoProxy &document) {
const auto size = getImageSize(document.vattributes.v); const auto size = getImageSize(document.vattributes().v);
if (size.isEmpty()) { if (size.isEmpty()) {
return ImagePtr(); return ImagePtr();
} }
return Create(qs(document.vurl), size.width(), size.height()); return Create(qs(document.vurl()), size.width(), size.height());
} }
ImagePtr Create(const MTPDwebDocument &document, QSize box) { ImagePtr Create(const MTPDwebDocument &document, QSize box) {
//const auto size = getImageSize(document.vattributes.v); //const auto size = getImageSize(document.vattributes().v);
//if (size.isEmpty()) { //if (size.isEmpty()) {
// return ImagePtr(); // return ImagePtr();
//} //}
// We don't use size from WebDocument, because it is not reliable. // We don't use size from WebDocument, because it is not reliable.
// It can be > 0 and different from the real size that we get in upload.WebFile result. // It can be > 0 and different from the real size that we get in upload.WebFile result.
auto filesize = 0; // document.vsize.v; auto filesize = 0; // document.vsize().v;
return Create( return Create(
WebFileLocation( WebFileLocation(
document.vurl.v, document.vurl().v,
document.vaccess_hash.v), document.vaccess_hash().v),
box, box,
filesize); filesize);
} }
ImagePtr Create(const MTPDwebDocumentNoProxy &document, QSize box) { ImagePtr Create(const MTPDwebDocumentNoProxy &document, QSize box) {
//const auto size = getImageSize(document.vattributes.v); //const auto size = getImageSize(document.vattributes().v);
//if (size.isEmpty()) { //if (size.isEmpty()) {
// return ImagePtr(); // return ImagePtr();
//} //}
return Create(qs(document.vurl), box); return Create(qs(document.vurl()), box);
} }
ImagePtr Create(const MTPWebDocument &document) { ImagePtr Create(const MTPWebDocument &document) {

View file

@ -84,36 +84,36 @@ StorageFileLocation::StorageFileLocation(
: _dcId(dcId) { : _dcId(dcId) {
tl.match([&](const MTPDinputFileLocation &data) { tl.match([&](const MTPDinputFileLocation &data) {
_type = Type::Legacy; _type = Type::Legacy;
_volumeId = data.vvolume_id.v; _volumeId = data.vvolume_id().v;
_localId = data.vlocal_id.v; _localId = data.vlocal_id().v;
_accessHash = data.vsecret.v; _accessHash = data.vsecret().v;
_fileReference = data.vfile_reference.v; _fileReference = data.vfile_reference().v;
}, [&](const MTPDinputEncryptedFileLocation &data) { }, [&](const MTPDinputEncryptedFileLocation &data) {
_type = Type::Encrypted; _type = Type::Encrypted;
_id = data.vid.v; _id = data.vid().v;
_accessHash = data.vaccess_hash.v; _accessHash = data.vaccess_hash().v;
}, [&](const MTPDinputDocumentFileLocation &data) { }, [&](const MTPDinputDocumentFileLocation &data) {
_type = Type::Document; _type = Type::Document;
_id = data.vid.v; _id = data.vid().v;
_accessHash = data.vaccess_hash.v; _accessHash = data.vaccess_hash().v;
_fileReference = data.vfile_reference.v; _fileReference = data.vfile_reference().v;
_sizeLetter = data.vthumb_size.v.isEmpty() _sizeLetter = data.vthumb_size().v.isEmpty()
? uint8(0) ? uint8(0)
: uint8(data.vthumb_size.v[0]); : uint8(data.vthumb_size().v[0]);
}, [&](const MTPDinputSecureFileLocation &data) { }, [&](const MTPDinputSecureFileLocation &data) {
_type = Type::Secure; _type = Type::Secure;
_id = data.vid.v; _id = data.vid().v;
_accessHash = data.vaccess_hash.v; _accessHash = data.vaccess_hash().v;
}, [&](const MTPDinputTakeoutFileLocation &data) { }, [&](const MTPDinputTakeoutFileLocation &data) {
_type = Type::Takeout; _type = Type::Takeout;
}, [&](const MTPDinputPhotoFileLocation &data) { }, [&](const MTPDinputPhotoFileLocation &data) {
_type = Type::Photo; _type = Type::Photo;
_id = data.vid.v; _id = data.vid().v;
_accessHash = data.vaccess_hash.v; _accessHash = data.vaccess_hash().v;
_fileReference = data.vfile_reference.v; _fileReference = data.vfile_reference().v;
_sizeLetter = data.vthumb_size.v.isEmpty() _sizeLetter = data.vthumb_size().v.isEmpty()
? char(0) ? char(0)
: data.vthumb_size.v[0]; : data.vthumb_size().v[0];
}, [&](const MTPDinputPeerPhotoFileLocation &data) { }, [&](const MTPDinputPeerPhotoFileLocation &data) {
_type = Type::PeerPhoto; _type = Type::PeerPhoto;
const auto fillPeer = base::overload([&]( const auto fillPeer = base::overload([&](
@ -122,45 +122,45 @@ StorageFileLocation::StorageFileLocation(
}, [&](const MTPDinputPeerSelf & data) { }, [&](const MTPDinputPeerSelf & data) {
_id = peerFromUser(self); _id = peerFromUser(self);
}, [&](const MTPDinputPeerChat & data) { }, [&](const MTPDinputPeerChat & data) {
_id = peerFromChat(data.vchat_id); _id = peerFromChat(data.vchat_id());
}, [&](const MTPDinputPeerUser & data) { }, [&](const MTPDinputPeerUser & data) {
_id = peerFromUser(data.vuser_id); _id = peerFromUser(data.vuser_id());
_accessHash = data.vaccess_hash.v; _accessHash = data.vaccess_hash().v;
}, [&](const MTPDinputPeerChannel & data) { }, [&](const MTPDinputPeerChannel & data) {
_id = peerFromChannel(data.vchannel_id); _id = peerFromChannel(data.vchannel_id());
_accessHash = data.vaccess_hash.v; _accessHash = data.vaccess_hash().v;
}); });
data.vpeer.match(fillPeer, [&]( data.vpeer().match(fillPeer, [&](
const MTPDinputPeerUserFromMessage &data) { const MTPDinputPeerUserFromMessage &data) {
data.vpeer.match(fillPeer, [&](auto &&) { data.vpeer().match(fillPeer, [&](auto &&) {
// Bad data provided. // Bad data provided.
_id = _accessHash = 0; _id = _accessHash = 0;
}); });
_inMessagePeerId = data.vuser_id.v; _inMessagePeerId = data.vuser_id().v;
_inMessageId = data.vmsg_id.v; _inMessageId = data.vmsg_id().v;
}, [&](const MTPDinputPeerChannelFromMessage &data) { }, [&](const MTPDinputPeerChannelFromMessage &data) {
data.vpeer.match(fillPeer, [&](auto &&) { data.vpeer().match(fillPeer, [&](auto &&) {
// Bad data provided. // Bad data provided.
_id = _accessHash = 0; _id = _accessHash = 0;
}); });
_inMessagePeerId = -data.vchannel_id.v; _inMessagePeerId = -data.vchannel_id().v;
_inMessageId = data.vmsg_id.v; _inMessageId = data.vmsg_id().v;
}); });
_volumeId = data.vvolume_id.v; _volumeId = data.vvolume_id().v;
_localId = data.vlocal_id.v; _localId = data.vlocal_id().v;
_sizeLetter = data.is_big() ? 'c' : 'a'; _sizeLetter = data.is_big() ? 'c' : 'a';
}, [&](const MTPDinputStickerSetThumb &data) { }, [&](const MTPDinputStickerSetThumb &data) {
_type = Type::StickerSetThumb; _type = Type::StickerSetThumb;
data.vstickerset.match([&](const MTPDinputStickerSetEmpty &data) { data.vstickerset().match([&](const MTPDinputStickerSetEmpty &data) {
_id = 0; _id = 0;
}, [&](const MTPDinputStickerSetID &data) { }, [&](const MTPDinputStickerSetID &data) {
_id = data.vid.v; _id = data.vid().v;
_accessHash = data.vaccess_hash.v; _accessHash = data.vaccess_hash().v;
}, [&](const MTPDinputStickerSetShortName &data) { }, [&](const MTPDinputStickerSetShortName &data) {
Unexpected("inputStickerSetShortName in StorageFileLocation()."); Unexpected("inputStickerSetShortName in StorageFileLocation().");
}); });
_volumeId = data.vvolume_id.v; _volumeId = data.vvolume_id().v;
_localId = data.vlocal_id.v; _localId = data.vlocal_id().v;
}); });
} }

View file

@ -1475,47 +1475,47 @@ EntitiesInText EntitiesFromMTP(const QVector<MTPMessageEntity> &entities) {
result.reserve(entities.size()); result.reserve(entities.size());
for_const (auto &entity, entities) { for_const (auto &entity, entities) {
switch (entity.type()) { switch (entity.type()) {
case mtpc_messageEntityUrl: { auto &d = entity.c_messageEntityUrl(); result.push_back({ EntityType::Url, d.voffset.v, d.vlength.v }); } break; case mtpc_messageEntityUrl: { auto &d = entity.c_messageEntityUrl(); result.push_back({ EntityType::Url, d.voffset().v, d.vlength().v }); } break;
case mtpc_messageEntityTextUrl: { auto &d = entity.c_messageEntityTextUrl(); result.push_back({ EntityType::CustomUrl, d.voffset.v, d.vlength.v, Clean(qs(d.vurl)) }); } break; case mtpc_messageEntityTextUrl: { auto &d = entity.c_messageEntityTextUrl(); result.push_back({ EntityType::CustomUrl, d.voffset().v, d.vlength().v, Clean(qs(d.vurl())) }); } break;
case mtpc_messageEntityEmail: { auto &d = entity.c_messageEntityEmail(); result.push_back({ EntityType::Email, d.voffset.v, d.vlength.v }); } break; case mtpc_messageEntityEmail: { auto &d = entity.c_messageEntityEmail(); result.push_back({ EntityType::Email, d.voffset().v, d.vlength().v }); } break;
case mtpc_messageEntityHashtag: { auto &d = entity.c_messageEntityHashtag(); result.push_back({ EntityType::Hashtag, d.voffset.v, d.vlength.v }); } break; case mtpc_messageEntityHashtag: { auto &d = entity.c_messageEntityHashtag(); result.push_back({ EntityType::Hashtag, d.voffset().v, d.vlength().v }); } break;
case mtpc_messageEntityCashtag: { auto &d = entity.c_messageEntityCashtag(); result.push_back({ EntityType::Cashtag, d.voffset.v, d.vlength.v }); } break; case mtpc_messageEntityCashtag: { auto &d = entity.c_messageEntityCashtag(); result.push_back({ EntityType::Cashtag, d.voffset().v, d.vlength().v }); } break;
case mtpc_messageEntityPhone: break; // Skipping phones. case mtpc_messageEntityPhone: break; // Skipping phones.
case mtpc_messageEntityMention: { auto &d = entity.c_messageEntityMention(); result.push_back({ EntityType::Mention, d.voffset.v, d.vlength.v }); } break; case mtpc_messageEntityMention: { auto &d = entity.c_messageEntityMention(); result.push_back({ EntityType::Mention, d.voffset().v, d.vlength().v }); } break;
case mtpc_messageEntityMentionName: { case mtpc_messageEntityMentionName: {
auto &d = entity.c_messageEntityMentionName(); auto &d = entity.c_messageEntityMentionName();
auto data = [&d] { auto data = [&d] {
if (auto user = Auth().data().userLoaded(d.vuser_id.v)) { if (auto user = Auth().data().userLoaded(d.vuser_id().v)) {
return MentionNameDataFromFields({ return MentionNameDataFromFields({
d.vuser_id.v, d.vuser_id().v,
user->accessHash() }); user->accessHash() });
} }
return MentionNameDataFromFields(d.vuser_id.v); return MentionNameDataFromFields(d.vuser_id().v);
}; };
result.push_back({ EntityType::MentionName, d.voffset.v, d.vlength.v, data() }); result.push_back({ EntityType::MentionName, d.voffset().v, d.vlength().v, data() });
} break; } break;
case mtpc_inputMessageEntityMentionName: { case mtpc_inputMessageEntityMentionName: {
auto &d = entity.c_inputMessageEntityMentionName(); auto &d = entity.c_inputMessageEntityMentionName();
auto data = ([&d]() -> QString { auto data = ([&d]() -> QString {
if (d.vuser_id.type() == mtpc_inputUserSelf) { if (d.vuser_id().type() == mtpc_inputUserSelf) {
return MentionNameDataFromFields(Auth().userId()); return MentionNameDataFromFields(Auth().userId());
} else if (d.vuser_id.type() == mtpc_inputUser) { } else if (d.vuser_id().type() == mtpc_inputUser) {
auto &user = d.vuser_id.c_inputUser(); auto &user = d.vuser_id().c_inputUser();
return MentionNameDataFromFields({ user.vuser_id.v, user.vaccess_hash.v }); return MentionNameDataFromFields({ user.vuser_id().v, user.vaccess_hash().v });
} }
return QString(); return QString();
})(); })();
if (!data.isEmpty()) { if (!data.isEmpty()) {
result.push_back({ EntityType::MentionName, d.voffset.v, d.vlength.v, data }); result.push_back({ EntityType::MentionName, d.voffset().v, d.vlength().v, data });
} }
} break; } break;
case mtpc_messageEntityBotCommand: { auto &d = entity.c_messageEntityBotCommand(); result.push_back({ EntityType::BotCommand, d.voffset.v, d.vlength.v }); } break; case mtpc_messageEntityBotCommand: { auto &d = entity.c_messageEntityBotCommand(); result.push_back({ EntityType::BotCommand, d.voffset().v, d.vlength().v }); } break;
case mtpc_messageEntityBold: { auto &d = entity.c_messageEntityBold(); result.push_back({ EntityType::Bold, d.voffset.v, d.vlength.v }); } break; case mtpc_messageEntityBold: { auto &d = entity.c_messageEntityBold(); result.push_back({ EntityType::Bold, d.voffset().v, d.vlength().v }); } break;
case mtpc_messageEntityItalic: { auto &d = entity.c_messageEntityItalic(); result.push_back({ EntityType::Italic, d.voffset.v, d.vlength.v }); } break; case mtpc_messageEntityItalic: { auto &d = entity.c_messageEntityItalic(); result.push_back({ EntityType::Italic, d.voffset().v, d.vlength().v }); } break;
case mtpc_messageEntityUnderline: { auto &d = entity.c_messageEntityUnderline(); result.push_back({ EntityType::Underline, d.voffset.v, d.vlength.v }); } break; case mtpc_messageEntityUnderline: { auto &d = entity.c_messageEntityUnderline(); result.push_back({ EntityType::Underline, d.voffset().v, d.vlength().v }); } break;
case mtpc_messageEntityStrike: { auto &d = entity.c_messageEntityStrike(); result.push_back({ EntityType::StrikeOut, d.voffset.v, d.vlength.v }); } break; case mtpc_messageEntityStrike: { auto &d = entity.c_messageEntityStrike(); result.push_back({ EntityType::StrikeOut, d.voffset().v, d.vlength().v }); } break;
case mtpc_messageEntityCode: { auto &d = entity.c_messageEntityCode(); result.push_back({ EntityType::Code, d.voffset.v, d.vlength.v }); } break; case mtpc_messageEntityCode: { auto &d = entity.c_messageEntityCode(); result.push_back({ EntityType::Code, d.voffset().v, d.vlength().v }); } break;
case mtpc_messageEntityPre: { auto &d = entity.c_messageEntityPre(); result.push_back({ EntityType::Pre, d.voffset.v, d.vlength.v, Clean(qs(d.vlanguage)) }); } break; case mtpc_messageEntityPre: { auto &d = entity.c_messageEntityPre(); result.push_back({ EntityType::Pre, d.voffset().v, d.vlength().v, Clean(qs(d.vlanguage())) }); } break;
// #TODO entities // #TODO entities
} }
} }

View file

@ -450,7 +450,7 @@ void ChatBackground::checkUploadWallPaper() {
result.match([&](const MTPDwallPaper &data) { result.match([&](const MTPDwallPaper &data) {
_session->data().documentConvert( _session->data().documentConvert(
_session->data().document(documentId), _session->data().document(documentId),
data.vdocument); data.vdocument());
}); });
if (const auto paper = Data::WallPaper::Create(result)) { if (const auto paper = Data::WallPaper::Create(result)) {
setPaper(*paper); setPaper(*paper);

View file

@ -172,14 +172,13 @@ void PasscodeLockWidget::setInnerFocus() {
} }
TermsLock TermsLock::FromMTP(const MTPDhelp_termsOfService &data) { TermsLock TermsLock::FromMTP(const MTPDhelp_termsOfService &data) {
const auto minAge = data.vmin_age_confirm();
return { return {
bytes::make_vector(data.vid.c_dataJSON().vdata.v), bytes::make_vector(data.vid().c_dataJSON().vdata().v),
TextWithEntities { TextWithEntities {
TextUtilities::Clean(qs(data.vtext)), TextUtilities::Clean(qs(data.vtext())),
TextUtilities::EntitiesFromMTP(data.ventities.v) }, TextUtilities::EntitiesFromMTP(data.ventities().v) },
(data.has_min_age_confirm() (minAge ? std::make_optional(minAge->v) : std::nullopt),
? base::make_optional(data.vmin_age_confirm.v)
: std::nullopt),
data.is_popup() data.is_popup()
}; };
} }

View file

@ -841,7 +841,7 @@ void PeerMenuAddChannelMembers(not_null<ChannelData*> channel) {
list list
) | ranges::view::transform([](const MTPChannelParticipant &p) { ) | ranges::view::transform([](const MTPChannelParticipant &p) {
return p.match([](const auto &data) { return p.match([](const auto &data) {
return data.vuser_id.v; return data.vuser_id().v;
}); });
}) | ranges::view::transform([](UserId userId) { }) | ranges::view::transform([](UserId userId) {
return Auth().data().userLoaded(userId); return Auth().data().userLoaded(userId);

View file

@ -542,7 +542,6 @@
<(src_loc)/mtproto/session.h <(src_loc)/mtproto/session.h
<(src_loc)/mtproto/special_config_request.cpp <(src_loc)/mtproto/special_config_request.cpp
<(src_loc)/mtproto/special_config_request.h <(src_loc)/mtproto/special_config_request.h
<(src_loc)/mtproto/type_utils.cpp
<(src_loc)/mtproto/type_utils.h <(src_loc)/mtproto/type_utils.h
<(src_loc)/overview/overview_layout.cpp <(src_loc)/overview/overview_layout.cpp
<(src_loc)/overview/overview_layout.h <(src_loc)/overview/overview_layout.h