From 6ee5d55e73eb82523b95dbade98c17f6a636247d Mon Sep 17 00:00:00 2001 From: RadRussianRus Date: Sun, 11 Sep 2022 04:43:46 +0300 Subject: [PATCH] [Improvement] Convert tg://user?id= to mentions if possible --- .../SourceFiles/api/api_text_entities.cpp | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/Telegram/SourceFiles/api/api_text_entities.cpp b/Telegram/SourceFiles/api/api_text_entities.cpp index a782d6153..abe8b066a 100644 --- a/Telegram/SourceFiles/api/api_text_entities.cpp +++ b/Telegram/SourceFiles/api/api_text_entities.cpp @@ -13,6 +13,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_session.h" #include "data/data_document.h" #include "data/data_user.h" +#include "base/qthelp_regex.h" +#include "base/qthelp_url.h" namespace Api { namespace { @@ -155,7 +157,43 @@ MTPVector EntitiesToMTP( auto length = MTP_int(entity.length()); switch (entity.type()) { case EntityType::Url: v.push_back(MTP_messageEntityUrl(offset, length)); break; - case EntityType::CustomUrl: v.push_back(MTP_messageEntityTextUrl(offset, length, MTP_string(entity.data()))); break; + case EntityType::CustomUrl: { + auto url = entity.data(); + auto inputUser = [&](const QString &data) -> MTPInputUser { + const auto trimmed = url.trimmed(); + if (trimmed.isEmpty()) { + return MTP_inputUserEmpty(); + } + auto regex = QRegularExpression( + QString::fromUtf8("^(?i)tg://user\\?(.+)"), + QRegularExpression::UseUnicodePropertiesOption); + regex.optimize(); + const auto match = regex.match(trimmed); + if (!match.hasMatch() || match.capturedStart() != 0) { + return MTP_inputUserEmpty(); + } + const auto parsed = qthelp::url_parse_params(match.captured(1), qthelp::UrlParamNameTransform::ToLower); + const auto qstr_uid = parsed.value("id"); + if (qstr_uid.isEmpty()) { + return MTP_inputUserEmpty(); + } + bool success; + UserId uid = qstr_uid.toLongLong(&success); + if (success && session) { + if (uid == session->userId()) { + return MTP_inputUserSelf(); + } else if (const auto user = session->data().userLoaded(uid)) { + return MTP_inputUser(MTP_long(uid.bare), MTP_long(user->accessHash())); + } + } + return MTP_inputUserEmpty(); + }(url); + if (inputUser.type() != mtpc_inputUserEmpty) { + v.push_back(MTP_inputMessageEntityMentionName(offset, length, inputUser)); + } else { + v.push_back(MTP_messageEntityTextUrl(offset, length, MTP_string(url))); + } + } break; case EntityType::Email: v.push_back(MTP_messageEntityEmail(offset, length)); break; case EntityType::Hashtag: v.push_back(MTP_messageEntityHashtag(offset, length)); break; case EntityType::Cashtag: v.push_back(MTP_messageEntityCashtag(offset, length)); break;