/* 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 "settings/settings_privacy_controllers.h" #include "settings/settings_common.h" #include "lang/lang_keys.h" #include "apiwrap.h" #include "mainwidget.h" #include "main/main_session.h" #include "data/data_user.h" #include "data/data_session.h" #include "data/data_changes.h" #include "core/application.h" #include "core/core_settings.h" #include "history/admin_log/history_admin_log_item.h" #include "history/view/history_view_element.h" #include "history/view/history_view_message.h" #include "history/history_item_components.h" #include "history/history_message.h" #include "history/history.h" #include "calls/calls_instance.h" #include "base/unixtime.h" #include "base/event_filter.h" #include "ui/chat/chat_theme.h" #include "ui/chat/chat_style.h" #include "ui/widgets/checkbox.h" #include "ui/wrap/padding_wrap.h" #include "ui/wrap/vertical_layout.h" #include "ui/wrap/slide_wrap.h" #include "ui/image/image_prepare.h" #include "ui/cached_round_corners.h" #include "ui/text/format_values.h" // Ui::FormatPhone #include "ui/text/text_utilities.h" #include "window/section_widget.h" #include "window/window_controller.h" #include "window/window_session_controller.h" #include "boxes/peer_list_controllers.h" #include "ui/boxes/confirm_box.h" #include "settings/settings_privacy_security.h" #include "facades.h" #include "styles/style_chat.h" #include "styles/style_boxes.h" #include "styles/style_settings.h" #include #include namespace Settings { namespace { using UserPrivacy = Api::UserPrivacy; using PrivacyRule = Api::UserPrivacy::Rule; using Option = EditPrivacyBox::Option; [[nodiscard]] QString PublicLinkByPhone(not_null user) { return user->session().createInternalLinkFull('+' + user->phone()); } class BlockPeerBoxController final : public ChatsListBoxController { public: explicit BlockPeerBoxController(not_null session); Main::Session &session() const override; void rowClicked(not_null row) override; void setBlockPeerCallback(Fn peer)> callback) { _blockPeerCallback = std::move(callback); } protected: void prepareViewHook() override; std::unique_ptr createRow(not_null history) override; void updateRowHook(not_null row) override { updateIsBlocked(row, row->peer()); delegate()->peerListUpdateRow(row); } private: void updateIsBlocked(not_null row, PeerData *peer) const; const not_null _session; Fn peer)> _blockPeerCallback; }; BlockPeerBoxController::BlockPeerBoxController( not_null session) : ChatsListBoxController(session) , _session(session) { } Main::Session &BlockPeerBoxController::session() const { return *_session; } void BlockPeerBoxController::prepareViewHook() { delegate()->peerListSetTitle(tr::lng_blocked_list_add_title()); session().changes().peerUpdates( Data::PeerUpdate::Flag::IsBlocked ) | rpl::start_with_next([=](const Data::PeerUpdate &update) { if (auto row = delegate()->peerListFindRow(update.peer->id.value)) { updateIsBlocked(row, update.peer); delegate()->peerListUpdateRow(row); } }, lifetime()); } void BlockPeerBoxController::updateIsBlocked(not_null row, PeerData *peer) const { auto blocked = peer->isBlocked(); row->setDisabledState(blocked ? PeerListRow::State::DisabledChecked : PeerListRow::State::Active); if (blocked) { row->setCustomStatus(tr::lng_blocked_list_already_blocked(tr::now)); } else { row->clearCustomStatus(); } } void BlockPeerBoxController::rowClicked(not_null row) { _blockPeerCallback(row->peer()); } auto BlockPeerBoxController::createRow(not_null history) -> std::unique_ptr { if (!history->peer->isUser() || history->peer->isServiceUser() || history->peer->isSelf() || history->peer->isRepliesChat()) { return nullptr; } auto row = std::make_unique(history); updateIsBlocked(row.get(), history->peer); return row; } AdminLog::OwnedItem GenerateForwardedItem( not_null delegate, not_null history, const QString &text) { Expects(history->peer->isUser()); using Flag = MTPDmessage::Flag; const auto flags = Flag::f_from_id | Flag::f_fwd_from; const auto item = MTP_message( MTP_flags(flags), MTP_int(0), // Not used (would've been trimmed to 32 bits). peerToMTP(history->peer->id), peerToMTP(history->peer->id), MTP_messageFwdHeader( MTP_flags(MTPDmessageFwdHeader::Flag::f_from_id), peerToMTP(history->session().userPeerId()), MTPstring(), // from_name MTP_int(base::unixtime::now()), MTPint(), // channel_post MTPstring(), // post_author MTPPeer(), // saved_from_peer MTPint(), // saved_from_msg_id MTPstring()), // psa_type MTPlong(), // via_bot_id MTPMessageReplyHeader(), MTP_int(base::unixtime::now()), // date MTP_string(text), MTPMessageMedia(), MTPReplyMarkup(), MTPVector(), MTPint(), // views MTPint(), // forwards MTPMessageReplies(), MTPint(), // edit_date MTPstring(), // post_author MTPlong(), // grouped_id MTPMessageReactions(), MTPVector(), MTPint() // ttl_period ).match([&](const MTPDmessage &data) { return history->makeMessage( history->nextNonHistoryEntryId(), data, MessageFlag::FakeHistoryItem); }, [](auto &&) -> not_null { Unexpected("Type in GenerateForwardedItem."); }); return AdminLog::OwnedItem(delegate, item); } struct ForwardedTooltip { QRect geometry; Fn paint; }; [[nodiscard]] ForwardedTooltip PrepareForwardedTooltip( not_null view, Option value) { // This breaks HistoryView::Element encapsulation :( const auto forwarded = view->data()->Get(); const auto availableWidth = view->width() - st::msgMargin.left() - st::msgMargin.right(); const auto bubbleWidth = ranges::min({ availableWidth, view->maxWidth(), st::msgMaxWidth }); const auto innerWidth = bubbleWidth - st::msgPadding.left() - st::msgPadding.right(); const auto phrase = tr::lng_forwarded( tr::now, lt_user, view->data()->history()->session().user()->name); const auto kReplacementPosition = QChar(0x0001); const auto possiblePosition = tr::lng_forwarded( tr::now, lt_user, QString(1, kReplacementPosition) ).indexOf(kReplacementPosition); const auto position = (possiblePosition >= 0 && possiblePosition < phrase.size()) ? possiblePosition : 0; const auto before = phrase.mid(0, position); const auto skip = st::msgMargin.left() + st::msgPadding.left(); const auto small = forwarded->text.countHeight(innerWidth) < 2 * st::msgServiceFont->height; const auto nameLeft = skip + (small ? st::msgServiceFont->width(before) : 0); const auto right = skip + innerWidth; const auto text = [&] { switch (value) { case Option::Everyone: return tr::lng_edit_privacy_forwards_sample_everyone(tr::now); case Option::Contacts: return tr::lng_edit_privacy_forwards_sample_contacts(tr::now); case Option::Nobody: return tr::lng_edit_privacy_forwards_sample_nobody(tr::now); } Unexpected("Option value in ForwardsPrivacyController."); }(); const auto &font = st::defaultToast.style.font; const auto textWidth = font->width(text); const auto arrowSkip = st::settingsForwardPrivacyArrowSkip; const auto arrowSize = st::settingsForwardPrivacyArrowSize; const auto padding = st::settingsForwardPrivacyTooltipPadding; const auto rect = QRect(0, 0, textWidth, font->height).marginsAdded( padding ).translated(padding.left(), padding.top()); const auto top = st::settingsForwardPrivacyPadding + view->marginTop() + st::msgPadding.top() - arrowSize - rect.height(); const auto left1 = std::min(nameLeft, right - rect.width()); const auto left2 = std::max(left1, skip); const auto left = left2; const auto arrowLeft1 = nameLeft + arrowSkip; const auto arrowLeft2 = std::min( arrowLeft1, std::max((left + right) / 2, right - arrowSkip)); const auto arrowLeft = arrowLeft2; const auto geometry = rect.translated(left, top); const auto line = st::lineWidth; const auto full = geometry.marginsAdded( { line, line, line, line + arrowSize }); const auto origin = full.topLeft(); const auto paint = [=](Painter &p) { p.translate(-origin); Ui::FillRoundRect( p, geometry, st::toastBg, ImageRoundRadius::Large); p.setFont(font); p.setPen(st::toastFg); p.drawText( geometry.x() + padding.left(), geometry.y() + padding.top() + font->ascent, text); const auto bottom = full.y() + full.height() - line; QPainterPath path; path.moveTo(arrowLeft - arrowSize, bottom - arrowSize); path.lineTo(arrowLeft, bottom); path.lineTo(arrowLeft + arrowSize, bottom - arrowSize); path.lineTo(arrowLeft - arrowSize, bottom - arrowSize); { PainterHighQualityEnabler hq(p); p.setPen(Qt::NoPen); p.fillPath(path, st::toastBg); } }; return { .geometry = full, .paint = paint }; } } // namespace BlockedBoxController::BlockedBoxController( not_null window) : _window(window) { } Main::Session &BlockedBoxController::session() const { return _window->session(); } void BlockedBoxController::prepare() { delegate()->peerListSetTitle(tr::lng_blocked_list_title()); setDescriptionText(tr::lng_contacts_loading(tr::now)); delegate()->peerListRefreshRows(); session().changes().peerUpdates( Data::PeerUpdate::Flag::IsBlocked ) | rpl::start_with_next([=](const Data::PeerUpdate &update) { handleBlockedEvent(update.peer); }, lifetime()); session().api().blockedPeers().slice( ) | rpl::take( 1 ) | rpl::start_with_next([=](const Api::BlockedPeers::Slice &result) { setDescriptionText(tr::lng_blocked_list_about(tr::now)); applySlice(result); loadMoreRows(); }, lifetime()); } void BlockedBoxController::loadMoreRows() { if (_allLoaded) { return; } session().api().blockedPeers().request( _offset, crl::guard(&_guard, [=](const Api::BlockedPeers::Slice &slice) { applySlice(slice); })); } void BlockedBoxController::rowClicked(not_null row) { const auto peer = row->peer(); crl::on_main(&peer->session(), [=] { Ui::showPeerHistory(peer, ShowAtUnreadMsgId); }); } void BlockedBoxController::rowRightActionClicked(not_null row) { session().api().blockedPeers().unblock(row->peer()); } void BlockedBoxController::applySlice(const Api::BlockedPeers::Slice &slice) { if (slice.list.empty()) { _allLoaded = true; } _offset += slice.list.size(); for (const auto &item : slice.list) { if (const auto peer = session().data().peerLoaded(item.id)) { appendRow(peer); peer->setIsBlocked(true); } } if (_offset >= slice.total) { _allLoaded = true; } delegate()->peerListRefreshRows(); } void BlockedBoxController::handleBlockedEvent(not_null user) { if (user->isBlocked()) { if (prependRow(user)) { delegate()->peerListRefreshRows(); delegate()->peerListScrollToTop(); } } else if (auto row = delegate()->peerListFindRow(user->id.value)) { delegate()->peerListRemoveRow(row); delegate()->peerListRefreshRows(); _rowsCountChanges.fire(delegate()->peerListFullRowsCount()); } } void BlockedBoxController::BlockNewPeer( not_null window) { auto controller = std::make_unique( &window->session()); auto initBox = [=, controller = controller.get()]( not_null box) { controller->setBlockPeerCallback([=](not_null peer) { window->session().api().blockedPeers().block(peer); box->closeBox(); }); box->addButton(tr::lng_cancel(), [box] { box->closeBox(); }); }; window->show( Box(std::move(controller), std::move(initBox)), Ui::LayerOption::KeepOther); } bool BlockedBoxController::appendRow(not_null peer) { if (delegate()->peerListFindRow(peer->id.value)) { return false; } delegate()->peerListAppendRow(createRow(peer)); _rowsCountChanges.fire(delegate()->peerListFullRowsCount()); return true; } bool BlockedBoxController::prependRow(not_null peer) { if (delegate()->peerListFindRow(peer->id.value)) { return false; } delegate()->peerListPrependRow(createRow(peer)); _rowsCountChanges.fire(delegate()->peerListFullRowsCount()); return true; } std::unique_ptr BlockedBoxController::createRow( not_null peer) const { auto row = std::make_unique(peer); row->setActionLink(tr::lng_blocked_list_unblock(tr::now)); const auto status = [&] { const auto user = peer->asUser(); if (!user) { return tr::lng_group_status(tr::now); } else if (!user->phone().isEmpty()) { return Ui::FormatPhone(user->phone()); } else if (!user->username.isEmpty()) { return '@' + user->username; } else if (user->isBot()) { return tr::lng_status_bot(tr::now); } return tr::lng_blocked_list_unknown_phone(tr::now); }(); row->setCustomStatus(status); return row; } rpl::producer BlockedBoxController::rowsCountChanges() const { return _rowsCountChanges.events(); } PhoneNumberPrivacyController::PhoneNumberPrivacyController( not_null controller) : _controller(controller) { } UserPrivacy::Key PhoneNumberPrivacyController::key() { return Key::PhoneNumber; } rpl::producer PhoneNumberPrivacyController::title() { return tr::lng_edit_privacy_phone_number_title(); } rpl::producer PhoneNumberPrivacyController::optionsTitleKey() { return tr::lng_edit_privacy_phone_number_header(); } rpl::producer PhoneNumberPrivacyController::warning() { using namespace rpl::mappers; const auto self = _controller->session().user(); return rpl::combine( _phoneNumberOption.value(), _addedByPhone.value(), (_1 == Option::Nobody) && (_2 != Option::Everyone) ) | rpl::map([=](bool onlyContactsSee) { return onlyContactsSee ? tr::lng_edit_privacy_phone_number_contacts( Ui::Text::WithEntities) : rpl::combine( tr::lng_edit_privacy_phone_number_warning(), tr::lng_username_link() ) | rpl::map([=](const QString &warning, const QString &added) { auto base = TextWithEntities{ warning + "\n\n" + added + "\n", }; const auto link = PublicLinkByPhone(self); return base.append(Ui::Text::Link(link, link)); }); }) | rpl::flatten_latest(); } void PhoneNumberPrivacyController::prepareWarningLabel( not_null warning) { warning->setClickHandlerFilter([=]( const ClickHandlerPtr &link, Qt::MouseButton button) { if (button == Qt::LeftButton) { QGuiApplication::clipboard()->setText(PublicLinkByPhone( _controller->session().user())); _controller->window().showToast( tr::lng_username_copied(tr::now)); return false; } return true; }); } rpl::producer PhoneNumberPrivacyController::exceptionButtonTextKey( Exception exception) { switch (exception) { case Exception::Always: return tr::lng_edit_privacy_phone_number_always_empty(); case Exception::Never: return tr::lng_edit_privacy_phone_number_never_empty(); } Unexpected("Invalid exception value."); } rpl::producer PhoneNumberPrivacyController::exceptionBoxTitle( Exception exception) { switch (exception) { case Exception::Always: return tr::lng_edit_privacy_phone_number_always_title(); case Exception::Never: return tr::lng_edit_privacy_phone_number_never_title(); } Unexpected("Invalid exception value."); } rpl::producer PhoneNumberPrivacyController::exceptionsDescription() { return tr::lng_edit_privacy_phone_number_exceptions(); } object_ptr PhoneNumberPrivacyController::setupMiddleWidget( not_null controller, not_null parent, rpl::producer