1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
|
/*
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 "inline_bots/bot_attach_web_view.h"
#include "data/data_user.h"
#include "data/data_file_origin.h"
#include "data/data_document.h"
#include "data/data_document_media.h"
#include "data/data_session.h"
#include "main/main_session.h"
#include "main/main_domain.h"
#include "storage/storage_domain.h"
#include "info/profile/info_profile_values.h"
#include "ui/boxes/confirm_box.h"
#include "ui/toasts/common_toasts.h"
#include "ui/chat/attach/attach_bot_webview.h"
#include "ui/widgets/checkbox.h"
#include "ui/widgets/dropdown_menu.h"
#include "ui/widgets/popup_menu.h"
#include "ui/widgets/menu/menu_item_base.h"
#include "ui/text/text_utilities.h"
#include "ui/effects/ripple_animation.h"
#include "ui/painter.h"
#include "window/themes/window_theme.h"
#include "window/window_controller.h"
#include "window/window_session_controller.h"
#include "webview/webview_interface.h"
#include "core/application.h"
#include "core/local_url_handlers.h"
#include "ui/basic_click_handlers.h"
#include "history/history.h"
#include "history/history_item.h"
#include "payments/payments_checkout_process.h"
#include "storage/storage_account.h"
#include "boxes/peer_list_controllers.h"
#include "lang/lang_keys.h"
#include "base/random.h"
#include "base/timer_rpl.h"
#include "apiwrap.h"
#include "styles/style_boxes.h"
#include "styles/style_menu_icons.h"
#include <QSvgRenderer>
namespace InlineBots {
namespace {
constexpr auto kProlongTimeout = 60 * crl::time(1000);
struct ParsedBot {
UserData *bot = nullptr;
bool inactive = false;
};
[[nodiscard]] bool IsSame(
const std::optional<Api::SendAction> &a,
const Api::SendAction &b) {
// Check fields that are sent to API in bot attach webview requests.
return a.has_value()
&& (a->history == b.history)
&& (a->replyTo == b.replyTo)
&& (a->topicRootId == b.topicRootId)
&& (a->options.sendAs == b.options.sendAs)
&& (a->options.silent == b.options.silent);
}
[[nodiscard]] DocumentData *ResolveIcon(
not_null<Main::Session*> session,
const MTPDattachMenuBot &data) {
for (const auto &icon : data.vicons().v) {
const auto document = icon.match([&](
const MTPDattachMenuBotIcon &data
) -> DocumentData* {
if (data.vname().v == "default_static") {
return session->data().processDocument(data.vicon()).get();
}
return nullptr;
});
if (document) {
return document;
}
}
return nullptr;
}
[[nodiscard]] PeerTypes ResolvePeerTypes(
const QVector<MTPAttachMenuPeerType> &types) {
auto result = PeerTypes();
for (const auto &type : types) {
result |= type.match([&](const MTPDattachMenuPeerTypeSameBotPM &) {
return PeerType::SameBot;
}, [&](const MTPDattachMenuPeerTypeBotPM &) {
return PeerType::Bot;
}, [&](const MTPDattachMenuPeerTypePM &) {
return PeerType::User;
}, [&](const MTPDattachMenuPeerTypeChat &) {
return PeerType::Group;
}, [&](const MTPDattachMenuPeerTypeBroadcast &) {
return PeerType::Broadcast;
});
}
return result;
}
[[nodiscard]] std::optional<AttachWebViewBot> ParseAttachBot(
not_null<Main::Session*> session,
const MTPAttachMenuBot &bot) {
auto result = bot.match([&](const MTPDattachMenuBot &data) {
const auto user = session->data().userLoaded(UserId(data.vbot_id()));
const auto good = user
&& user->isBot()
&& user->botInfo->supportsAttachMenu;
return good
? AttachWebViewBot{
.user = user,
.icon = ResolveIcon(session, data),
.name = qs(data.vshort_name()),
.types = ResolvePeerTypes(data.vpeer_types().v),
.inactive = data.is_inactive(),
.hasSettings = data.is_has_settings(),
.requestWriteAccess = data.is_request_write_access(),
} : std::optional<AttachWebViewBot>();
});
if (result && result->icon) {
result->icon->forceToCache(true);
}
return result;
}
void ShowChooseBox(
not_null<Window::SessionController*> controller,
PeerTypes types,
Fn<void(not_null<Data::Thread*>)> callback) {
const auto weak = std::make_shared<QPointer<Ui::BoxContent>>();
auto done = [=](not_null<Data::Thread*> thread) mutable {
if (const auto strong = *weak) {
strong->closeBox();
}
callback(thread);
};
auto filter = [=](not_null<Data::Thread*> thread) -> bool {
const auto peer = thread->peer();
if (!Data::CanSend(thread, ChatRestriction::SendInline, false)) {
return false;
} else if (const auto user = peer->asUser()) {
if (user->isBot()) {
return (types & PeerType::Bot);
} else {
return (types & PeerType::User);
}
} else if (peer->isBroadcast()) {
return (types & PeerType::Broadcast);
} else {
return (types & PeerType::Group);
}
};
auto initBox = [](not_null<PeerListBox*> box) {
box->addButton(tr::lng_cancel(), [box] {
box->closeBox();
});
};
*weak = controller->show(Box<PeerListBox>(
std::make_unique<ChooseRecipientBoxController>(
&controller->session(),
std::move(done),
std::move(filter)),
std::move(initBox)), Ui::LayerOption::KeepOther);
}
[[nodiscard]] base::flat_set<not_null<AttachWebView*>> &ActiveWebViews() {
static auto result = base::flat_set<not_null<AttachWebView*>>();
return result;
}
class BotAction final : public Ui::Menu::ItemBase {
public:
BotAction(
not_null<Ui::RpWidget*> parent,
const style::Menu &st,
const AttachWebViewBot &bot,
Fn<void()> callback);
bool isEnabled() const override;
not_null<QAction*> action() const override;
[[nodiscard]] rpl::producer<bool> forceShown() const;
void handleKeyPress(not_null<QKeyEvent*> e) override;
private:
void contextMenuEvent(QContextMenuEvent *e) override;
QPoint prepareRippleStartPosition() const override;
QImage prepareRippleMask() const override;
int contentHeight() const override;
void prepare();
void validateIcon();
void paint(Painter &p);
const not_null<QAction*> _dummyAction;
const style::Menu &_st;
const AttachWebViewBot _bot;
base::unique_qptr<Ui::PopupMenu> _menu;
rpl::event_stream<bool> _forceShown;
Ui::Text::String _text;
QImage _mask;
QImage _icon;
int _textWidth = 0;
const int _height;
};
BotAction::BotAction(
not_null<Ui::RpWidget*> parent,
const style::Menu &st,
const AttachWebViewBot &bot,
Fn<void()> callback)
: ItemBase(parent, st)
, _dummyAction(new QAction(parent))
, _st(st)
, _bot(bot)
, _height(_st.itemPadding.top()
+ _st.itemStyle.font->height
+ _st.itemPadding.bottom()) {
setAcceptBoth(false);
initResizeHook(parent->sizeValue());
setClickedCallback(std::move(callback));
paintRequest(
) | rpl::start_with_next([=] {
Painter p(this);
paint(p);
}, lifetime());
style::PaletteChanged(
) | rpl::start_with_next([=] {
_icon = QImage();
update();
}, lifetime());
enableMouseSelecting();
prepare();
}
void BotAction::validateIcon() {
if (_mask.isNull()) {
if (!_bot.media || !_bot.media->loaded()) {
return;
}
auto icon = QSvgRenderer(_bot.media->bytes());
if (!icon.isValid()) {
_mask = QImage(
QSize(1, 1) * style::DevicePixelRatio(),
QImage::Format_ARGB32_Premultiplied);
_mask.fill(Qt::transparent);
} else {
const auto size = style::ConvertScale(icon.defaultSize());
_mask = QImage(
size * style::DevicePixelRatio(),
QImage::Format_ARGB32_Premultiplied);
_mask.setDevicePixelRatio(style::DevicePixelRatio());
_mask.fill(Qt::transparent);
{
auto p = QPainter(&_mask);
icon.render(&p, QRect(QPoint(), size));
}
_mask = Images::Colored(std::move(_mask), QColor(255, 255, 255));
}
}
if (_icon.isNull()) {
_icon = style::colorizeImage(_mask, st::menuIconColor);
}
}
void BotAction::paint(Painter &p) {
validateIcon();
const auto selected = isSelected();
if (selected && _st.itemBgOver->c.alpha() < 255) {
p.fillRect(0, 0, width(), _height, _st.itemBg);
}
p.fillRect(0, 0, width(), _height, selected ? _st.itemBgOver : _st.itemBg);
if (isEnabled()) {
paintRipple(p, 0, 0);
}
if (!_icon.isNull()) {
p.drawImage(_st.itemIconPosition, _icon);
}
p.setPen(selected ? _st.itemFgOver : _st.itemFg);
_text.drawLeftElided(
p,
_st.itemPadding.left(),
_st.itemPadding.top(),
_textWidth,
width());
}
void BotAction::prepare() {
_text.setMarkedText(_st.itemStyle, { _bot.name });
const auto textWidth = _text.maxWidth();
const auto &padding = _st.itemPadding;
const auto goodWidth = padding.left()
+ textWidth
+ padding.right();
const auto w = std::clamp(goodWidth, _st.widthMin, _st.widthMax);
_textWidth = w - (goodWidth - textWidth);
setMinWidth(w);
update();
}
bool BotAction::isEnabled() const {
return true;
}
not_null<QAction*> BotAction::action() const {
return _dummyAction;
}
void BotAction::contextMenuEvent(QContextMenuEvent *e) {
_menu = nullptr;
_menu = base::make_unique_q<Ui::PopupMenu>(
this,
st::popupMenuWithIcons);
_menu->addAction(tr::lng_bot_remove_from_menu(tr::now), [=] {
_bot.user->session().attachWebView().removeFromMenu(_bot.user);
}, &st::menuIconDelete);
QObject::connect(_menu, &QObject::destroyed, [=] {
_forceShown.fire(false);
});
_forceShown.fire(true);
_menu->popup(e->globalPos());
e->accept();
}
QPoint BotAction::prepareRippleStartPosition() const {
return mapFromGlobal(QCursor::pos());
}
QImage BotAction::prepareRippleMask() const {
return Ui::RippleAnimation::RectMask(size());
}
int BotAction::contentHeight() const {
return _height;
}
rpl::producer<bool> BotAction::forceShown() const {
return _forceShown.events();
}
void BotAction::handleKeyPress(not_null<QKeyEvent*> e) {
if (!isSelected()) {
return;
}
const auto key = e->key();
if (key == Qt::Key_Enter || key == Qt::Key_Return) {
setClicked(Ui::Menu::TriggeredSource::Keyboard);
}
}
} // namespace
bool PeerMatchesTypes(
not_null<PeerData*> peer,
not_null<UserData*> bot,
PeerTypes types) {
if (const auto user = peer->asUser()) {
return (user == bot)
? (types & PeerType::SameBot)
: user->isBot()
? (types & PeerType::Bot)
: (types & PeerType::User);
} else if (peer->isBroadcast()) {
return (types & PeerType::Broadcast);
}
return (types & PeerType::Group);
}
PeerTypes ParseChooseTypes(QStringView choose) {
auto result = PeerTypes();
for (const auto &entry : choose.split(QChar(' '))) {
if (entry == u"users"_q) {
result |= PeerType::User;
} else if (entry == u"bots"_q) {
result |= PeerType::Bot;
} else if (entry == u"groups"_q) {
result |= PeerType::Group;
} else if (entry == u"channels"_q) {
result |= PeerType::Broadcast;
}
}
return result;
}
AttachWebView::AttachWebView(not_null<Main::Session*> session)
: _session(session) {
}
AttachWebView::~AttachWebView() {
ActiveWebViews().remove(this);
}
void AttachWebView::request(
const Api::SendAction &action,
const QString &botUsername,
const QString &startCommand) {
if (botUsername.isEmpty()) {
return;
}
const auto username = _bot ? _bot->username() : _botUsername;
if (IsSame(_action, action)
&& username.toLower() == botUsername.toLower()
&& _startCommand == startCommand) {
if (_panel) {
_panel->requestActivate();
}
return;
}
cancel();
_action = action;
_botUsername = botUsername;
_startCommand = startCommand;
resolve();
}
void AttachWebView::request(
Window::SessionController *controller,
const Api::SendAction &action,
not_null<UserData*> bot,
const WebViewButton &button) {
if (IsSame(_action, action) && _bot == bot) {
if (_panel) {
_panel->requestActivate();
} else if (_requestId) {
return;
}
}
cancel();
_bot = bot;
_action = action;
if (controller) {
confirmOpen(controller, [=] {
request(button);
});
} else {
request(button);
}
}
void AttachWebView::request(const WebViewButton &button) {
Expects(_action.has_value() && _bot != nullptr);
_startCommand = button.startCommand;
using Flag = MTPmessages_RequestWebView::Flag;
const auto flags = Flag::f_theme_params
| (button.url.isEmpty() ? Flag(0) : Flag::f_url)
| (_startCommand.isEmpty() ? Flag(0) : Flag::f_start_param)
| (_action->replyTo ? Flag::f_reply_to_msg_id : Flag(0))
| (_action->topicRootId ? Flag::f_top_msg_id : Flag(0))
| (_action->options.sendAs ? Flag::f_send_as : Flag(0))
| (_action->options.silent ? Flag::f_silent : Flag(0));
_requestId = _session->api().request(MTPmessages_RequestWebView(
MTP_flags(flags),
_action->history->peer->input,
_bot->inputUser,
MTP_bytes(button.url),
MTP_string(_startCommand),
MTP_dataJSON(MTP_bytes(Window::Theme::WebViewParams().json)),
MTP_string("tdesktop"),
MTP_int(_action->replyTo.bare),
MTP_int(_action->topicRootId.bare),
(_action->options.sendAs
? _action->options.sendAs->input
: MTP_inputPeerEmpty())
)).done([=](const MTPWebViewResult &result) {
_requestId = 0;
result.match([&](const MTPDwebViewResultUrl &data) {
show(
data.vquery_id().v,
qs(data.vurl()),
button.text,
button.fromMenu || button.url.isEmpty());
});
}).fail([=](const MTP::Error &error) {
_requestId = 0;
if (error.type() == u"BOT_INVALID"_q) {
requestBots();
}
}).send();
}
void AttachWebView::cancel() {
ActiveWebViews().remove(this);
_session->api().request(base::take(_requestId)).cancel();
_session->api().request(base::take(_prolongId)).cancel();
_panel = nullptr;
_action = std::nullopt;
_bot = nullptr;
_botUsername = QString();
_startCommand = QString();
}
void AttachWebView::requestBots() {
if (_botsRequestId) {
return;
}
_botsRequestId = _session->api().request(MTPmessages_GetAttachMenuBots(
MTP_long(_botsHash)
)).done([=](const MTPAttachMenuBots &result) {
_botsRequestId = 0;
result.match([&](const MTPDattachMenuBotsNotModified &) {
}, [&](const MTPDattachMenuBots &data) {
_session->data().processUsers(data.vusers());
_botsHash = data.vhash().v;
_attachBots.clear();
_attachBots.reserve(data.vbots().v.size());
for (const auto &bot : data.vbots().v) {
if (auto parsed = ParseAttachBot(_session, bot)) {
if (!parsed->inactive) {
if (const auto icon = parsed->icon) {
parsed->media = icon->createMediaView();
icon->save(Data::FileOrigin(), {});
}
_attachBots.push_back(std::move(*parsed));
}
}
}
_attachBotsUpdates.fire({});
});
}).fail([=] {
_botsRequestId = 0;
}).send();
}
void AttachWebView::requestAddToMenu(
const std::optional<Api::SendAction> &action,
not_null<UserData*> bot,
const QString &startCommand,
Window::SessionController *controller,
PeerTypes chooseTypes) {
if (!bot->isBot() || !bot->botInfo->supportsAttachMenu) {
Ui::ShowMultilineToast({
.text = { tr::lng_bot_menu_not_supported(tr::now) },
});
return;
}
_addToMenuChooseController = base::make_weak(controller);
_addToMenuStartCommand = startCommand;
_addToMenuChooseTypes = chooseTypes;
_addToMenuAction = action;
if (_addToMenuId) {
if (_addToMenuBot == bot) {
return;
}
_session->api().request(base::take(_addToMenuId)).cancel();
}
_addToMenuBot = bot;
_addToMenuId = _session->api().request(MTPmessages_GetAttachMenuBot(
bot->inputUser
)).done([=](const MTPAttachMenuBotsBot &result) {
_addToMenuId = 0;
const auto bot = base::take(_addToMenuBot);
const auto contextAction = base::take(_addToMenuAction);
const auto chooseTypes = base::take(_addToMenuChooseTypes);
const auto startCommand = base::take(_addToMenuStartCommand);
const auto chooseController = base::take(_addToMenuChooseController);
const auto open = [=](PeerTypes types) {
if (const auto useTypes = chooseTypes & types) {
if (const auto strong = chooseController.get()) {
const auto done = [=](not_null<Data::Thread*> thread) {
strong->showThread(thread);
request(
nullptr,
Api::SendAction(thread),
bot,
{ .startCommand = startCommand });
};
ShowChooseBox(strong, useTypes, done);
}
return true;
} else if (!contextAction) {
return false;
}
request(
nullptr,
*contextAction,
bot,
{ .startCommand = startCommand });
return true;
};
result.match([&](const MTPDattachMenuBotsBot &data) {
_session->data().processUsers(data.vusers());
if (const auto parsed = ParseAttachBot(_session, data.vbot())) {
if (bot == parsed->user) {
const auto types = parsed->types;
if (parsed->inactive) {
confirmAddToMenu(*parsed, [=] {
open(types);
});
} else {
requestBots();
if (!open(types)) {
Ui::ShowMultilineToast({
.text = {
tr::lng_bot_menu_already_added(tr::now) },
});
}
}
}
}
});
}).fail([=] {
_addToMenuId = 0;
_addToMenuBot = nullptr;
_addToMenuAction = std::nullopt;
_addToMenuStartCommand = QString();
Ui::ShowMultilineToast({
.text = { tr::lng_bot_menu_not_supported(tr::now) },
});
}).send();
}
void AttachWebView::removeFromMenu(not_null<UserData*> bot) {
toggleInMenu(bot, ToggledState::Removed, [=] {
Ui::ShowMultilineToast({
.text = { tr::lng_bot_remove_from_menu_done(tr::now) },
});
});
}
void AttachWebView::resolve() {
resolveUsername(_botUsername, [=](not_null<PeerData*> bot) {
_bot = bot->asUser();
if (!_bot) {
Ui::ShowMultilineToast({
.text = { tr::lng_bot_menu_not_supported(tr::now) }
});
return;
}
requestAddToMenu(_action, _bot, _startCommand);
});
}
void AttachWebView::resolveUsername(
const QString &username,
Fn<void(not_null<PeerData*>)> done) {
if (const auto peer = _session->data().peerByUsername(username)) {
done(peer);
return;
}
_session->api().request(base::take(_requestId)).cancel();
_requestId = _session->api().request(MTPcontacts_ResolveUsername(
MTP_string(username)
)).done([=](const MTPcontacts_ResolvedPeer &result) {
_requestId = 0;
result.match([&](const MTPDcontacts_resolvedPeer &data) {
_session->data().processUsers(data.vusers());
_session->data().processChats(data.vchats());
if (const auto peerId = peerFromMTP(data.vpeer())) {
done(_session->data().peer(peerId));
}
});
}).fail([=](const MTP::Error &error) {
_requestId = 0;
if (error.code() == 400) {
Ui::ShowMultilineToast({
.text = {
tr::lng_username_not_found(tr::now, lt_user, username),
},
});
}
}).send();
}
void AttachWebView::requestSimple(
not_null<Window::SessionController*> controller,
not_null<UserData*> bot,
const WebViewButton &button) {
cancel();
_bot = bot;
_action = Api::SendAction(bot->owner().history(bot));
confirmOpen(controller, [=] {
requestSimple(button);
});
}
void AttachWebView::requestSimple(const WebViewButton &button) {
using Flag = MTPmessages_RequestSimpleWebView::Flag;
_requestId = _session->api().request(MTPmessages_RequestSimpleWebView(
MTP_flags(Flag::f_theme_params),
_bot->inputUser,
MTP_bytes(button.url),
MTP_dataJSON(MTP_bytes(Window::Theme::WebViewParams().json)),
MTP_string("tdesktop")
)).done([=](const MTPSimpleWebViewResult &result) {
_requestId = 0;
result.match([&](const MTPDsimpleWebViewResultUrl &data) {
const auto queryId = uint64();
show(queryId, qs(data.vurl()), button.text);
});
}).fail([=](const MTP::Error &error) {
_requestId = 0;
}).send();
}
void AttachWebView::requestMenu(
not_null<Window::SessionController*> controller,
not_null<UserData*> bot) {
cancel();
_bot = bot;
_action = Api::SendAction(bot->owner().history(bot));
const auto url = bot->botInfo->botMenuButtonUrl;
const auto text = bot->botInfo->botMenuButtonText;
confirmOpen(controller, [=] {
using Flag = MTPmessages_RequestWebView::Flag;
_requestId = _session->api().request(MTPmessages_RequestWebView(
MTP_flags(Flag::f_theme_params
| Flag::f_url
| Flag::f_from_bot_menu
| (_action->replyTo? Flag::f_reply_to_msg_id : Flag(0))
| (_action->topicRootId ? Flag::f_top_msg_id : Flag(0))
| (_action->options.sendAs ? Flag::f_send_as : Flag(0))
| (_action->options.silent ? Flag::f_silent : Flag(0))),
_action->history->peer->input,
_bot->inputUser,
MTP_string(url),
MTPstring(), // start_param
MTP_dataJSON(MTP_bytes(Window::Theme::WebViewParams().json)),
MTP_string("tdesktop"),
MTP_int(_action->replyTo.bare),
MTP_int(_action->topicRootId.bare),
(_action->options.sendAs
? _action->options.sendAs->input
: MTP_inputPeerEmpty())
)).done([=](const MTPWebViewResult &result) {
_requestId = 0;
result.match([&](const MTPDwebViewResultUrl &data) {
show(data.vquery_id().v, qs(data.vurl()), text);
});
}).fail([=](const MTP::Error &error) {
_requestId = 0;
if (error.type() == u"BOT_INVALID"_q) {
requestBots();
}
}).send();
});
}
void AttachWebView::confirmOpen(
not_null<Window::SessionController*> controller,
Fn<void()> done) {
if (!_bot) {
return;
} else if (_bot->isVerified()
|| _bot->session().local().isBotTrustedOpenWebView(_bot->id)) {
done();
return;
}
const auto callback = [=] {
_bot->session().local().markBotTrustedOpenWebView(_bot->id);
controller->hideLayer();
done();
};
controller->show(Ui::MakeConfirmBox({
.text = tr::lng_allow_bot_webview(
tr::now,
lt_bot_name,
Ui::Text::Bold(_bot->name()),
Ui::Text::RichLangValue),
.confirmed = callback,
.confirmText = tr::lng_box_ok(),
}));
}
void AttachWebView::ClearAll() {
while (!ActiveWebViews().empty()) {
ActiveWebViews().front()->cancel();
}
}
void AttachWebView::show(
uint64 queryId,
const QString &url,
const QString &buttonText,
bool allowClipboardRead) {
Expects(_bot != nullptr && _action.has_value());
const auto close = crl::guard(this, [=] {
crl::on_main(this, [=] { cancel(); });
});
const auto sendData = crl::guard(this, [=](QByteArray data) {
if (!_action || _action->history->peer != _bot || queryId) {
return;
}
const auto randomId = base::RandomValue<uint64>();
_session->api().request(MTPmessages_SendWebViewData(
_bot->inputUser,
MTP_long(randomId),
MTP_string(buttonText),
MTP_bytes(data)
)).done([=](const MTPUpdates &result) {
_session->api().applyUpdates(result);
}).send();
crl::on_main(this, [=] { cancel(); });
});
const auto handleLocalUri = [close](QString uri) {
const auto local = Core::TryConvertUrlToLocal(uri);
if (uri == local || Core::InternalPassportLink(local)) {
return local.startsWith(u"tg://"_q);
} else if (!local.startsWith(u"tg://"_q, Qt::CaseInsensitive)) {
return false;
}
UrlClickHandler::Open(local, {});
close();
return true;
};
const auto panel = std::make_shared<
base::weak_ptr<Ui::BotWebView::Panel>>(nullptr);
const auto handleInvoice = [=, session = _session](QString slug) {
using Result = Payments::CheckoutResult;
const auto reactivate = [=](Result result) {
if (const auto strong = panel->get()) {
strong->invoiceClosed(slug, [&] {
switch (result) {
case Result::Paid: return "paid";
case Result::Failed: return "failed";
case Result::Pending: return "pending";
case Result::Cancelled: return "cancelled";
}
Unexpected("Payments::CheckoutResult value.");
}());
}
};
if (const auto strong = panel->get()) {
strong->hideForPayment();
}
Payments::CheckoutProcess::Start(session, slug, reactivate);
};
auto title = Info::Profile::NameValue(_bot);
ActiveWebViews().emplace(this);
using Button = Ui::BotWebView::MenuButton;
const auto attached = ranges::find(
_attachBots,
not_null{ _bot },
&AttachWebViewBot::user);
const auto name = (attached != end(_attachBots))
? attached->name
: _bot->name();
const auto hasSettings = (attached != end(_attachBots))
&& !attached->inactive
&& attached->hasSettings;
const auto hasOpenBot = !_action || (_bot != _action->history->peer);
const auto hasRemoveFromMenu = (attached != end(_attachBots))
&& !attached->inactive;
const auto buttons = (hasSettings ? Button::Settings : Button::None)
| (hasOpenBot ? Button::OpenBot : Button::None)
| (hasRemoveFromMenu ? Button::RemoveFromMenu : Button::None);
const auto bot = _bot;
const auto handleMenuButton = crl::guard(this, [=](Button button) {
switch (button) {
case Button::OpenBot:
close();
if (bot->session().windows().empty()) {
Core::App().domain().activate(&bot->session().account());
}
if (!bot->session().windows().empty()) {
const auto window = bot->session().windows().front();
window->showPeerHistory(bot);
window->window().activate();
}
break;
case Button::RemoveFromMenu:
if (const auto strong = panel->get()) {
const auto done = crl::guard(this, [=] {
removeFromMenu(bot);
close();
if (const auto active = Core::App().activeWindow()) {
active->activate();
}
});
strong->showBox(Ui::MakeConfirmBox({
tr::lng_bot_remove_from_menu_sure(
tr::now,
lt_bot,
Ui::Text::Bold(name),
Ui::Text::WithEntities),
done,
}));
}
break;
}
});
_panel = Ui::BotWebView::Show({
.url = url,
.userDataPath = _session->domain().local().webviewDataPath(),
.title = std::move(title),
.bottom = rpl::single('@' + _bot->username()),
.handleLocalUri = handleLocalUri,
.handleInvoice = handleInvoice,
.sendData = sendData,
.close = close,
.phone = _session->user()->phone(),
.menuButtons = buttons,
.handleMenuButton = handleMenuButton,
.themeParams = [] { return Window::Theme::WebViewParams(); },
.allowClipboardRead = allowClipboardRead,
});
*panel = _panel.get();
started(queryId);
}
void AttachWebView::started(uint64 queryId) {
Expects(_action.has_value() && _bot != nullptr);
_session->data().webViewResultSent(
) | rpl::filter([=](const Data::Session::WebViewResultSent &sent) {
return (sent.queryId == queryId);
}) | rpl::start_with_next([=] {
cancel();
}, _panel->lifetime());
base::timer_each(
kProlongTimeout
) | rpl::start_with_next([=] {
using Flag = MTPmessages_ProlongWebView::Flag;
_session->api().request(base::take(_prolongId)).cancel();
_prolongId = _session->api().request(MTPmessages_ProlongWebView(
MTP_flags(Flag(0)
| (_action->replyTo ? Flag::f_reply_to_msg_id : Flag(0))
| (_action->topicRootId ? Flag::f_top_msg_id : Flag(0))
| (_action->options.sendAs ? Flag::f_send_as : Flag(0))
| (_action->options.silent ? Flag::f_silent : Flag(0))),
_action->history->peer->input,
_bot->inputUser,
MTP_long(queryId),
MTP_int(_action->replyTo.bare),
MTP_int(_action->topicRootId.bare),
(_action->options.sendAs
? _action->options.sendAs->input
: MTP_inputPeerEmpty())
)).done([=] {
_prolongId = 0;
}).send();
}, _panel->lifetime());
}
void AttachWebView::confirmAddToMenu(
AttachWebViewBot bot,
Fn<void()> callback) {
const auto active = Core::App().activeWindow();
if (!active) {
return;
}
_confirmAddBox = active->show(Box([=](not_null<Ui::GenericBox*> box) {
const auto allowed = std::make_shared<Ui::Checkbox*>();
const auto done = [=](Fn<void()> close) {
const auto state = ((*allowed) && (*allowed)->checked())
? ToggledState::AllowedToWrite
: ToggledState::Added;
toggleInMenu(bot.user, state, [=] {
if (callback) {
callback();
}
Ui::ShowMultilineToast({
.text = { tr::lng_bot_add_to_menu_done(tr::now) },
});
});
close();
};
Ui::ConfirmBox(box, {
tr::lng_bot_add_to_menu(
tr::now,
lt_bot,
Ui::Text::Bold(bot.name),
Ui::Text::WithEntities),
done,
});
if (bot.requestWriteAccess) {
(*allowed) = box->addRow(
object_ptr<Ui::Checkbox>(
box,
tr::lng_url_auth_allow_messages(
tr::now,
lt_bot,
Ui::Text::Bold(bot.name),
Ui::Text::WithEntities),
true,
st::urlAuthCheckbox),
style::margins(
st::boxRowPadding.left(),
st::boxPhotoCaptionSkip,
st::boxRowPadding.right(),
st::boxPhotoCaptionSkip));
(*allowed)->setAllowTextLines();
}
}));
}
void AttachWebView::toggleInMenu(
not_null<UserData*> bot,
ToggledState state,
Fn<void()> callback) {
using Flag = MTPmessages_ToggleBotInAttachMenu::Flag;
_session->api().request(MTPmessages_ToggleBotInAttachMenu(
MTP_flags((state == ToggledState::AllowedToWrite)
? Flag::f_write_allowed
: Flag()),
bot->inputUser,
MTP_bool(state != ToggledState::Removed)
)).done([=] {
_requestId = 0;
requestBots();
if (callback) {
callback();
}
}).fail([=] {
cancel();
}).send();
}
std::unique_ptr<Ui::DropdownMenu> MakeAttachBotsMenu(
not_null<QWidget*> parent,
not_null<PeerData*> peer,
Fn<Api::SendAction()> actionFactory,
Fn<void(bool)> attach) {
if (!Data::CanSend(peer, ChatRestriction::SendInline)) {
return nullptr;
}
auto result = std::make_unique<Ui::DropdownMenu>(
parent,
st::dropdownMenuWithIcons);
const auto bots = &peer->session().attachWebView();
const auto raw = result.get();
auto minimal = 0;
if (Data::CanSend(peer, ChatRestriction::SendPhotos, false)) {
++minimal;
raw->addAction(tr::lng_attach_photo_or_video(tr::now), [=] {
attach(true);
}, &st::menuIconPhoto);
}
const auto fileTypes = ChatRestriction::SendVideos
| ChatRestriction::SendGifs
| ChatRestriction::SendStickers
| ChatRestriction::SendMusic
| ChatRestriction::SendFiles;
if (Data::CanSendAnyOf(peer, fileTypes)) {
++minimal;
raw->addAction(tr::lng_attach_document(tr::now), [=] {
attach(false);
}, &st::menuIconFile);
}
for (const auto &bot : bots->attachBots()) {
if (!PeerMatchesTypes(peer, bot.user, bot.types)) {
continue;
}
const auto callback = [=] {
bots->request(
nullptr,
actionFactory(),
bot.user,
{ .fromMenu = true });
};
auto action = base::make_unique_q<BotAction>(
raw,
raw->menu()->st(),
bot,
callback);
action->forceShown(
) | rpl::start_with_next([=](bool shown) {
if (shown) {
raw->setAutoHiding(false);
} else {
raw->hideAnimated();
raw->setAutoHiding(true);
}
}, action->lifetime());
raw->addAction(std::move(action));
}
if (raw->actions().size() <= minimal) {
return nullptr;
}
return result;
}
} // namespace InlineBots
|