std::unique_ptr<Result> Result::create(uint64 queryId, const MTPBotInlineResult &mtpData) { using StringToTypeMap = QMap<QString, Result::Type>; static StaticNeverFreedPointer<StringToTypeMap> stringToTypeMap{ ([]() -> StringToTypeMap* { auto result = std::make_unique<StringToTypeMap>(); result->insert(qsl("photo"), Result::Type::Photo); result->insert(qsl("video"), Result::Type::Video); result->insert(qsl("audio"), Result::Type::Audio); result->insert(qsl("voice"), Result::Type::Audio); result->insert(qsl("sticker"), Result::Type::Sticker); result->insert(qsl("file"), Result::Type::File); result->insert(qsl("gif"), Result::Type::Gif); result->insert(qsl("article"), Result::Type::Article); result->insert(qsl("contact"), Result::Type::Contact); result->insert(qsl("venue"), Result::Type::Venue); result->insert(qsl("geo"), Result::Type::Geo); result->insert(qsl("game"), Result::Type::Game); return result.release(); })() }; auto getInlineResultType = [](const MTPBotInlineResult &inlineResult) -> Type { QString type; switch (inlineResult.type()) { case mtpc_botInlineResult: type = qs(inlineResult.c_botInlineResult().vtype); break; case mtpc_botInlineMediaResult: type = qs(inlineResult.c_botInlineMediaResult().vtype); break; } return stringToTypeMap->value(type, Type::Unknown); }; Type type = getInlineResultType(mtpData); if (type == Type::Unknown) { return nullptr; } auto result = std::make_unique<Result>(Creator{ queryId, type }); const MTPBotInlineMessage *message = nullptr; switch (mtpData.type()) { case mtpc_botInlineResult: { const auto &r = mtpData.c_botInlineResult(); result->_id = qs(r.vid); if (r.has_title()) result->_title = qs(r.vtitle); if (r.has_description()) result->_description = qs(r.vdescription); if (r.has_url()) result->_url = qs(r.vurl); if (r.has_thumb()) { result->_thumb = ImagePtr(r.vthumb, result->thumbBox()); } if (r.has_content()) { result->_content_url = GetContentUrl(r.vcontent); if (result->_type == Type::Photo) { result->_photo = Auth().data().photoFromWeb( r.vcontent, result->_thumb); } else { result->_document = Auth().data().documentFromWeb( result->adjustAttributes(r.vcontent), result->_thumb); } } message = &r.vsend_message; } break; case mtpc_botInlineMediaResult: { const auto &r = mtpData.c_botInlineMediaResult(); result->_id = qs(r.vid); if (r.has_title()) result->_title = qs(r.vtitle); if (r.has_description()) result->_description = qs(r.vdescription); if (r.has_photo()) { result->_photo = Auth().data().photo(r.vphoto); } if (r.has_document()) { result->_document = Auth().data().document(r.vdocument); } message = &r.vsend_message; } break; } auto badAttachment = (result->_photo && result->_photo->full->isNull()) || (result->_document && !result->_document->isValid()); if (!message) { return nullptr; } // Ensure required media fields for layouts. if (result->_type == Type::Photo) { if (!result->_photo) { return nullptr; } } else if (result->_type == Type::Audio || result->_type == Type::File || result->_type == Type::Video || result->_type == Type::Sticker || result->_type == Type::Gif) { if (!result->_document) { return nullptr; } } switch (message->type()) { case mtpc_botInlineMessageMediaAuto: { auto &r = message->c_botInlineMessageMediaAuto(); auto entities = r.has_entities() ? TextUtilities::EntitiesFromMTP(r.ventities.v) : EntitiesInText(); if (result->_type == Type::Photo) { if (!result->_photo) { return nullptr; } result->sendData = std::make_unique<internal::SendPhoto>(result->_photo, qs(r.vmessage), entities); } else if (result->_type == Type::Game) { result->createGame(); result->sendData = std::make_unique<internal::SendGame>(result->_game); } else { if (!result->_document) { return nullptr; } result->sendData = std::make_unique<internal::SendFile>(result->_document, qs(r.vmessage), entities); } if (r.has_reply_markup()) { result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(r.vreply_markup); } } break; case mtpc_botInlineMessageText: { auto &r = message->c_botInlineMessageText(); auto entities = r.has_entities() ? TextUtilities::EntitiesFromMTP(r.ventities.v) : EntitiesInText(); result->sendData = std::make_unique<internal::SendText>(qs(r.vmessage), entities, r.is_no_webpage()); if (result->_type == Type::Photo) { if (!result->_photo) { return nullptr; } } else if (result->_type == Type::Audio || result->_type == Type::File || result->_type == Type::Video || result->_type == Type::Sticker || result->_type == Type::Gif) { if (!result->_document) { return nullptr; } } if (r.has_reply_markup()) { result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(r.vreply_markup); } } break; case mtpc_botInlineMessageMediaGeo: { // #TODO layer 72 save period and send live location?.. auto &r = message->c_botInlineMessageMediaGeo(); if (r.vgeo.type() == mtpc_geoPoint) { result->sendData = std::make_unique<internal::SendGeo>(r.vgeo.c_geoPoint()); } else { badAttachment = true; } if (r.has_reply_markup()) { result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(r.vreply_markup); } } break; case mtpc_botInlineMessageMediaVenue: { auto &r = message->c_botInlineMessageMediaVenue(); 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)); } else { badAttachment = true; } if (r.has_reply_markup()) { result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(r.vreply_markup); } } break; case mtpc_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)); if (r.has_reply_markup()) { result->_mtpKeyboard = std::make_unique<MTPReplyMarkup>(r.vreply_markup); } } break; default: { badAttachment = true; } break; } if (badAttachment || !result->sendData || !result->sendData->isValid()) { return nullptr; } LocationCoords location; if (result->getLocationCoords(&location)) { int32 w = st::inlineThumbSize, h = st::inlineThumbSize; int32 zoom = 13, scale = 1; if (cScale() == dbisTwo || cRetina()) { scale = 2; w /= 2; h /= 2; } auto coords = location.latAsString() + ',' + location.lonAsString(); QString url = qsl("https://maps.googleapis.com/maps/api/staticmap?center=") + coords + qsl("&zoom=%1&size=%2x%3&maptype=roadmap&scale=%4&markers=color:red|size:big|").arg(zoom).arg(w).arg(h).arg(scale) + coords + qsl("&sensor=false"); result->_locationThumb = ImagePtr(url); } return result; }
void ChannelData::applyEditBanned(not_null<UserData*> user, const MTPChannelBannedRights &oldRights, const MTPChannelBannedRights &newRights) { auto flags = Notify::PeerUpdate::Flag::BannedUsersChanged | Notify::PeerUpdate::Flag::None; auto isKicked = (newRights.c_channelBannedRights().vflags.v & MTPDchannelBannedRights::Flag::f_view_messages); auto isRestricted = !isKicked && (newRights.c_channelBannedRights().vflags.v != 0); if (mgInfo) { // If rights are empty - still remove admin? TODO check if (mgInfo->lastAdmins.contains(user)) { mgInfo->lastAdmins.remove(user); if (adminsCount() > 1) { setAdminsCount(adminsCount() - 1); } else { flags |= Notify::PeerUpdate::Flag::AdminsChanged; } } auto it = mgInfo->lastRestricted.find(user); if (isRestricted) { if (it == mgInfo->lastRestricted.cend()) { mgInfo->lastRestricted.emplace(user, MegagroupInfo::Restricted { newRights }); setRestrictedCount(restrictedCount() + 1); } else { it->second.rights = newRights; } } else { if (it != mgInfo->lastRestricted.cend()) { mgInfo->lastRestricted.erase(it); if (restrictedCount() > 0) { setRestrictedCount(restrictedCount() - 1); } } if (isKicked) { auto i = ranges::find(mgInfo->lastParticipants, user); if (i != mgInfo->lastParticipants.end()) { mgInfo->lastParticipants.erase(i); } if (membersCount() > 1) { setMembersCount(membersCount() - 1); } else { mgInfo->lastParticipantsStatus |= MegagroupInfo::LastParticipantsCountOutdated; mgInfo->lastParticipantsCount = 0; } setKickedCount(kickedCount() + 1); if (mgInfo->bots.contains(user)) { mgInfo->bots.remove(user); if (mgInfo->bots.empty() && mgInfo->botStatus > 0) { mgInfo->botStatus = -1; } } flags |= Notify::PeerUpdate::Flag::MembersChanged; Auth().data().removeMegagroupParticipant(this, user); } } Data::ChannelAdminChanges(this).feed(peerToUser(user->id), false); } else { if (isKicked) { if (membersCount() > 1) { setMembersCount(membersCount() - 1); flags |= Notify::PeerUpdate::Flag::MembersChanged; } setKickedCount(kickedCount() + 1); } } Notify::peerUpdatedDelayed(this, flags); }
EModRet HandleMessage(const CNick& Nick, CString sMessage) { if (!Nick.GetNick().Equals("Q") || !Nick.GetHost().Equals("CServe.quakenet.org")) return CONTINUE; sMessage.Trim(); #if Q_DEBUG_COMMUNICATION PutModule("[ZNC <-- Q] " + sMessage); #endif // WHOAMI if (sMessage.find("WHOAMI is only available to authed users") != CString::npos) { m_bAuthed = false; Auth(); m_bCatchResponse = m_bRequestedWhoami; } else if (sMessage.find("Information for user") != CString::npos) { m_bAuthed = true; m_msChanModes.clear(); m_bCatchResponse = m_bRequestedWhoami; m_bRequestedWhoami = true; } else if (m_bRequestedWhoami && sMessage.WildCmp("#*")) { CString sChannel = sMessage.Token(0); CString sFlags = sMessage.Token(1, true).Trim_n().TrimLeft_n("+"); m_msChanModes[sChannel] = sFlags; } else if (m_bRequestedWhoami && m_bCatchResponse && (sMessage.Equals("End of list.") || sMessage.Equals("account, or HELLO to create an account."))) { m_bRequestedWhoami = m_bCatchResponse = false; return HALT; } // AUTH else if (sMessage.Equals("Username or password incorrect.")) { m_bAuthed = false; PutModule("Auth failed: " + sMessage); return HALT; } else if (sMessage.WildCmp("You are now logged in as *.")) { m_bAuthed = true; PutModule("Auth successful: " + sMessage); WhoAmI(); return HALT; } else if (m_bRequestedChallenge && sMessage.Token(0).Equals("CHALLENGE")) { m_bRequestedChallenge = false; if (sMessage.find("not available once you have authed") != CString::npos) { m_bAuthed = true; } else { if (sMessage.find("HMAC-MD5") != CString::npos) { ChallengeAuth(sMessage.Token(1)); } else { PutModule("Auth failed: Q does not support HMAC-MD5 for CHALLENGEAUTH, falling back to standard AUTH."); SetUseChallenge(false); Auth(); } } return HALT; } // prevent buffering of Q's responses return !m_bCatchResponse && GetUser()->IsUserAttached() ? CONTINUE : HALT; }
virtual void OnModCommand(const CString& sLine) { CString sCommand = sLine.Token(0).AsLower(); if (sCommand == "help") { PutModule("The following commands are available:"); CTable Table; Table.AddColumn("Command"); Table.AddColumn("Description"); Table.AddRow(); Table.SetCell("Command", "Auth [<username> <password>]"); Table.SetCell("Description", "Tries to authenticate you with Q. Both parameters are optional."); Table.AddRow(); Table.SetCell("Command", "Cloak"); Table.SetCell("Description", "Tries to set usermode +x to hide your real hostname."); Table.AddRow(); Table.SetCell("Command", "Status"); Table.SetCell("Description", "Prints the current status of the module."); Table.AddRow(); Table.SetCell("Command", "Update"); Table.SetCell("Description", "Re-requests the current user information from Q."); Table.AddRow(); Table.SetCell("Command", "Set <setting> <value>"); Table.SetCell("Description", "Changes the value of the given setting. See the list of settings below."); Table.AddRow(); Table.SetCell("Command", "Get"); Table.SetCell("Description", "Prints out the current configuration. See the list of settings below."); PutModule(Table); PutModule("The following settings are available:"); CTable Table2; Table2.AddColumn("Setting"); Table2.AddColumn("Type"); Table2.AddColumn("Description"); Table2.AddRow(); Table2.SetCell("Setting", "Username"); Table2.SetCell("Type", "String"); Table2.SetCell("Description", "Your Q username."); Table2.AddRow(); Table2.SetCell("Setting", "Password"); Table2.SetCell("Type", "String"); Table2.SetCell("Description", "Your Q password."); Table2.AddRow(); Table2.SetCell("Setting", "UseCloakedHost"); Table2.SetCell("Type", "Boolean"); Table2.SetCell("Description", "Whether to cloak your hostname (+x) automatically on connect."); Table2.AddRow(); Table2.SetCell("Setting", "UseChallenge"); Table2.SetCell("Type", "Boolean"); Table2.SetCell("Description", "Whether to use the CHALLENGEAUTH mechanism to avoid sending passwords in cleartext."); Table2.AddRow(); Table2.SetCell("Setting", "RequestPerms"); Table2.SetCell("Type", "Boolean"); Table2.SetCell("Description", "Whether to request voice/op from Q on join/devoice/deop."); PutModule(Table2); PutModule("This module takes 2 optional parameters: <username> <password>"); PutModule("Module settings are stored between restarts."); } else if (sCommand == "set") { CString sSetting = sLine.Token(1).AsLower(); CString sValue = sLine.Token(2); if (sSetting.empty() || sValue.empty()) { PutModule("Syntax: Set <setting> <value>"); } else if (sSetting == "username") { SetUsername(sValue); PutModule("Username set"); } else if (sSetting == "password") { SetPassword(sValue); PutModule("Password set"); } else if (sSetting == "usecloakedhost") { SetUseCloakedHost(sValue.ToBool()); PutModule("UseCloakedHost set"); if (m_bUseCloakedHost && IsIRCConnected()) Cloak(); } else if (sSetting == "usechallenge") { SetUseChallenge(sValue.ToBool()); PutModule("UseChallenge set"); } else if (sSetting == "requestperms") { SetRequestPerms(sValue.ToBool()); PutModule("RequestPerms set"); } else PutModule("Unknown setting: " + sSetting); } else if (sCommand == "get" || sCommand == "list") { CTable Table; Table.AddColumn("Setting"); Table.AddColumn("Value"); Table.AddRow(); Table.SetCell("Setting", "Username"); Table.SetCell("Value", m_sUsername); Table.AddRow(); Table.SetCell("Setting", "Password"); Table.SetCell("Value", "*****"); // m_sPassword Table.AddRow(); Table.SetCell("Setting", "UseCloakedHost"); Table.SetCell("Value", CString(m_bUseCloakedHost)); Table.AddRow(); Table.SetCell("Setting", "UseChallenge"); Table.SetCell("Value", CString(m_bUseChallenge)); Table.AddRow(); Table.SetCell("Setting", "RequestPerms"); Table.SetCell("Value", CString(m_bRequestPerms)); PutModule(Table); } else if (sCommand == "status") { PutModule("Connected: " + CString(IsIRCConnected() ? "yes" : "no")); PutModule("Cloaked: " + CString(m_bCloaked ? "yes" : "no")); PutModule("Authed: " + CString(m_bAuthed ? "yes" : "no")); } else { // The following commands require an IRC connection. if (!IsIRCConnected()) { PutModule("Error: You are not connected to IRC."); return; } if (sCommand == "cloak") { if (!m_bCloaked) Cloak(); else PutModule("Error: You are already cloaked!"); } else if (sCommand == "auth") { if (!m_bAuthed) Auth(sLine.Token(1), sLine.Token(2)); else PutModule("Error: You are already authed!"); } else if (sCommand == "update") { WhoAmI(); PutModule("Update requested."); } else { PutModule("Unknown command. Try 'help'."); } } }
bool SpoofingTest(CSocket* socket,CDlgMain* dlg,char* buffer,int which,CDlgSettings* dlg2) { bool spoofing = true; dlg->console+=(which==1)?_T("\r\n*Starting Spoofing Test."):_T("\r\n*Starting Spoofing check 2."); dlg->UpdateData(FALSE); ScrollToBottom(dlg); if((which==2)&&(dlg2->auth_use)) { if(!Auth(socket,dlg,buffer,dlg2->auth_use,dlg2->set_authuser,dlg2->set_authpass)) { dlg->result_spoofing1 = _T("?"); dlg->MessageBox(_T("Couldn't test spoofing because provided authentication data are incorrect")); return false; } } else { Send(socket,dlg,"HELO mozilla"); Receive(socket,dlg,buffer); } CString temp; char* msg; temp = _T("MAIL FROM:<"); temp+=dlg2->set_spoofing_mailfrom; temp+=_T(">"); msg = StringToChar(temp); Send(socket,dlg,msg); Receive(socket,dlg,buffer); if(strcmp((const char*)MidStr(buffer,0,3),"250")!=0) spoofing = false; else { temp = _T("RCPT TO:<"); temp+=dlg2->set_spoofing_rpctto; temp+=_T(">"); msg = StringToChar(temp); Send(socket,dlg,msg); Receive(socket,dlg,buffer); if(strcmp((const char*)MidStr(buffer,0,3),"250")!=0) spoofing = false; else { Send(socket,dlg,"DATA"); Receive(socket,dlg,buffer); if(strcmp((const char*)MidStr(buffer,0,3),"354")!=0) spoofing = false; else { temp = _T("From: "); temp+=dlg2->set_spoofing_from; msg = StringToChar(temp); Send(socket,dlg,msg); temp = _T("To: "); temp+=dlg2->set_spoofing_to; msg = StringToChar(temp); Send(socket,dlg,msg); temp = _T("Reply-to: "); temp+=dlg2->set_spoofing_replyto; msg = StringToChar(temp); Send(socket,dlg,msg); temp = _T("Subject: "); temp+=dlg2->set_spoofing_subject; msg = StringToChar(temp); Send(socket,dlg,msg); Send(socket,dlg,""); POSITION lpos = dlg2->set_spoofing_message_list.GetHeadPosition(); CString line; for(int k=0;k<dlg2->set_spoofing_message_list.GetCount();k++) { line = dlg2->set_spoofing_message_list.GetNext(lpos); msg = StringToChar(line); Send(socket,dlg,msg); } Send(socket,dlg,"."); Receive(socket,dlg,buffer); spoofing = (strcmp((const char*)MidStr(buffer,0,3),"250")==0); Send(socket,dlg,"QUIT"); Receive(socket,dlg,buffer); } } } if(which==1) dlg->result_spoofing1 = spoofing?_T("YES"):_T("NO"); else dlg->result_spoofing2 = spoofing?_T("YES"):_T("NO"); return true; }
void PhotoData::cancel() { full->cancel(); Auth().data().notifyPhotoLayoutChanged(this); }
void Controller::showJumpToDate(Dialogs::Key chat, QDate requestedDate) { const auto currentPeerDate = [&] { if (const auto history = chat.history()) { if (history->scrollTopItem) { return history->scrollTopItem->dateTime().date(); } else if (history->loadedAtTop() && !history->isEmpty() && history->peer->migrateFrom()) { if (const auto migrated = App::historyLoaded(history->peer->migrateFrom())) { if (migrated->scrollTopItem) { // We're up in the migrated history. // So current date is the date of first message here. return history->blocks.front()->messages.front()->dateTime().date(); } } } else if (history->chatsListTimeId() != 0) { return ParseDateTime(history->chatsListTimeId()).date(); } } else if (const auto feed = chat.feed()) { /*if (chatScrollPosition(feed)) { // #TODO feeds save position } else */if (feed->chatsListTimeId() != 0) { return ParseDateTime(feed->chatsListTimeId()).date(); } } return QDate::currentDate(); }; const auto maxPeerDate = [](Dialogs::Key chat) { if (auto history = chat.history()) { if (const auto channel = history->peer->migrateTo()) { history = App::historyLoaded(channel); } if (history && history->chatsListTimeId() != 0) { return ParseDateTime(history->chatsListTimeId()).date(); } } else if (const auto feed = chat.feed()) { if (feed->chatsListTimeId() != 0) { return ParseDateTime(feed->chatsListTimeId()).date(); } } return QDate::currentDate(); }; const auto minPeerDate = [](Dialogs::Key chat) { const auto startDate = [] { // Telegram was launched in August 2013 :) return QDate(2013, 8, 1); }; if (const auto history = chat.history()) { if (const auto chat = history->peer->migrateFrom()) { if (const auto history = App::historyLoaded(chat)) { if (history->loadedAtTop()) { if (!history->isEmpty()) { return history->blocks.front()->messages.front()->dateTime().date(); } } else { return startDate(); } } } if (history->loadedAtTop()) { if (!history->isEmpty()) { return history->blocks.front()->messages.front()->dateTime().date(); } return QDate::currentDate(); } } else if (const auto feed = chat.feed()) { return startDate(); } return startDate(); }; const auto highlighted = requestedDate.isNull() ? currentPeerDate() : requestedDate; const auto month = highlighted; auto callback = [=](const QDate &date) { Auth().api().jumpToDate(chat, date); }; auto box = Box<CalendarBox>( month, highlighted, std::move(callback)); box->setMinDate(minPeerDate(chat)); box->setMaxDate(maxPeerDate(chat)); Ui::show(std::move(box)); }
QString ConvertTagToMimeTag(const QString &tagId) { if (IsMentionLink(tagId)) { return tagId + ':' + QString::number(Auth().userId()); } return tagId; }
int Controller::countThirdColumnWidthFromRatio(int bodyWidth) const { auto result = Auth().settings().thirdColumnWidth(); accumulate_max(result, st::columnMinimalWidthThird); accumulate_min(result, st::columnMaximalWidthThird); return result; }
void Controller::resizeForThirdSection() { if (Adaptive::ThreeColumn()) { return; } auto layout = computeColumnLayout(); auto tabbedSelectorSectionEnabled = Auth().settings().tabbedSelectorSectionEnabled(); auto thirdSectionInfoEnabled = Auth().settings().thirdSectionInfoEnabled(); Auth().settings().setTabbedSelectorSectionEnabled(false); Auth().settings().setThirdSectionInfoEnabled(false); auto wanted = countThirdColumnWidthFromRatio(layout.bodyWidth); auto minimal = st::columnMinimalWidthThird; auto extendBy = wanted; auto extendedBy = [&] { // Best - extend by third column without moving the window. // Next - extend by minimal third column without moving. // Next - show third column inside the window without moving. // Last - extend with moving. if (window()->canExtendNoMove(wanted)) { return window()->tryToExtendWidthBy(wanted); } else if (window()->canExtendNoMove(minimal)) { extendBy = minimal; return window()->tryToExtendWidthBy(minimal); } else if (layout.bodyWidth >= minimalThreeColumnWidth()) { return 0; } return window()->tryToExtendWidthBy(minimal); }(); if (extendedBy) { if (extendBy != Auth().settings().thirdColumnWidth()) { Auth().settings().setThirdColumnWidth(extendBy); } auto newBodyWidth = layout.bodyWidth + extendedBy; auto currentRatio = Auth().settings().dialogsWidthRatio(); Auth().settings().setDialogsWidthRatio( (currentRatio * layout.bodyWidth) / newBodyWidth); } auto savedValue = (extendedBy == extendBy) ? -1 : extendedBy; Auth().settings().setThirdSectionExtendedBy(savedValue); Auth().settings().setTabbedSelectorSectionEnabled( tabbedSelectorSectionEnabled); Auth().settings().setThirdSectionInfoEnabled( thirdSectionInfoEnabled); }
int Controller::countDialogsWidthFromRatio(int bodyWidth) const { auto result = qRound(bodyWidth * Auth().settings().dialogsWidthRatio()); accumulate_max(result, st::columnMinimalWidthLeft); // accumulate_min(result, st::columnMaximalWidthLeft); return result; }
TextWithTags::Tags ConvertEntitiesToTextTags(const EntitiesInText &entities) { TextWithTags::Tags result; if (entities.isEmpty()) { return result; } result.reserve(entities.size()); for (const auto &entity : entities) { const auto push = [&](const QString &tag) { result.push_back({ entity.offset(), entity.length(), tag }); }; switch (entity.type()) { case EntityType::MentionName: { auto match = QRegularExpression(R"(^(\d+\.\d+)$)").match(entity.data()); if (match.hasMatch()) { push(kMentionTagStart + entity.data()); } } break; case EntityType::CustomUrl: { const auto url = entity.data(); if (Ui::InputField::IsValidMarkdownLink(url) && !IsMentionLink(url)) { push(url); } } break; case EntityType::Bold: push(Ui::InputField::kTagBold); break; case EntityType::Italic: push(Ui::InputField::kTagItalic); break; // #TODO entities case EntityType::Code: push(Ui::InputField::kTagCode); break; case EntityType::Pre: push(Ui::InputField::kTagPre); break; } } return result; } std::unique_ptr<QMimeData> MimeDataFromText( const TextForMimeData &text) { if (text.empty()) { return nullptr; } auto result = std::make_unique<QMimeData>(); result->setText(text.expanded); auto tags = ConvertEntitiesToTextTags(text.rich.entities); if (!tags.isEmpty()) { for (auto &tag : tags) { tag.id = ConvertTagToMimeTag(tag.id); } result->setData( TextUtilities::TagsTextMimeType(), text.rich.text.toUtf8()); result->setData( TextUtilities::TagsMimeType(), TextUtilities::SerializeTags(tags)); } return result; } void SetClipboardText( const TextForMimeData &text, QClipboard::Mode mode) { if (auto data = MimeDataFromText(text)) { QApplication::clipboard()->setMimeData(data.release(), mode); } } Fn<bool( Ui::InputField::EditLinkSelection selection, QString text, QString link, EditLinkAction action)> DefaultEditLinkCallback( not_null<Ui::InputField*> field) { const auto weak = make_weak(field); return [=]( EditLinkSelection selection, QString text, QString link, EditLinkAction action) { if (action == EditLinkAction::Check) { return Ui::InputField::IsValidMarkdownLink(link) && !IsMentionLink(link); } Ui::show(Box<EditLinkBox>(text, link, [=]( const QString &text, const QString &link) { if (const auto strong = weak.data()) { strong->commitMarkdownLinkEdit(selection, text, link); } }), LayerOption::KeepOther); return true; }; } void InitMessageField( not_null<Window::Controller*> controller, not_null<Ui::InputField*> field) { field->setMinHeight(st::historySendSize.height() - 2 * st::historySendPadding); field->setMaxHeight(st::historyComposeFieldMaxHeight); field->setTagMimeProcessor(std::make_unique<FieldTagMimeProcessor>()); field->document()->setDocumentMargin(4.); field->setAdditionalMargin(ConvertScale(4) - 4); field->customTab(true); field->setInstantReplaces(Ui::InstantReplaces::Default()); field->setInstantReplacesEnabled(Global::ReplaceEmojiValue()); field->setMarkdownReplacesEnabled(rpl::single(true)); field->setEditLinkCallback(DefaultEditLinkCallback(field)); } bool HasSendText(not_null<const Ui::InputField*> field) { const auto &text = field->getTextWithTags().text; for (const auto ch : text) { const auto code = ch.unicode(); if (code != ' ' && code != '\n' && code != '\r' && !chReplacedBySpace(code)) { return true; } } return false; } InlineBotQuery ParseInlineBotQuery(not_null<const Ui::InputField*> field) { auto result = InlineBotQuery(); const auto &full = field->getTextWithTags(); const auto &text = full.text; const auto textLength = text.size(); auto inlineUsernameStart = 1; auto inlineUsernameLength = 0; if (textLength > 2 && text[0] == '@' && text[1].isLetter()) { inlineUsernameLength = 1; for (auto i = inlineUsernameStart + 1; i != textLength; ++i) { const auto ch = text[i]; if (ch.isLetterOrNumber() || ch.unicode() == '_') { ++inlineUsernameLength; continue; } else if (!ch.isSpace()) { inlineUsernameLength = 0; } break; } auto inlineUsernameEnd = inlineUsernameStart + inlineUsernameLength; auto inlineUsernameEqualsText = (inlineUsernameEnd == textLength); auto validInlineUsername = false; if (inlineUsernameEqualsText) { validInlineUsername = text.endsWith(qstr("bot")); } else if (inlineUsernameEnd < textLength && inlineUsernameLength) { validInlineUsername = text[inlineUsernameEnd].isSpace(); } if (validInlineUsername) { if (!full.tags.isEmpty() && (full.tags.front().offset < inlineUsernameStart + inlineUsernameLength)) { return InlineBotQuery(); } auto username = text.midRef(inlineUsernameStart, inlineUsernameLength); if (username != result.username) { result.username = username.toString(); if (const auto peer = Auth().data().peerByUsername(result.username)) { if (const auto user = peer->asUser()) { result.bot = peer->asUser(); } else { result.bot = nullptr; } result.lookingUpBot = false; } else { result.bot = nullptr; result.lookingUpBot = true; } } if (result.lookingUpBot) { result.query = QString(); return result; } else if (result.bot && (!result.bot->botInfo || result.bot->botInfo->inlinePlaceholder.isEmpty())) { result.bot = nullptr; } else { result.query = inlineUsernameEqualsText ? QString() : text.mid(inlineUsernameEnd + 1); return result; } } else { inlineUsernameLength = 0; } } if (inlineUsernameLength < 3) { result.bot = nullptr; result.username = QString(); } result.query = QString(); return result; }
void RedisAsyncConn::OnConnect() { m_state = CONNECTED; m_retry_times = 0; Auth(); }
void AdvancedWidget::onManageLocalStorage() { LocalStorageBox::Show(&Auth().data().cache()); }
void HistoryGroupedMedia::parentTextUpdated() { Auth().data().requestViewResize(_parent); }
rpl::producer<SparseIdsSlice> SearchController::simpleIdsSlice( PeerId peerId, MsgId aroundId, const Query &query, int limitBefore, int limitAfter) { Expects(peerId != 0); Expects(IsServerMsgId(aroundId) || (aroundId == 0)); Expects((aroundId != 0) || (limitBefore == 0 && limitAfter == 0)); Expects((query.peerId == peerId) || (query.migratedPeerId == peerId)); auto it = _cache.find(query); if (it == _cache.end()) { return [=](auto) { return rpl::lifetime(); }; } auto listData = (peerId == query.peerId) ? &it->second->peerData : &*it->second->migratedData; return [=](auto consumer) { auto lifetime = rpl::lifetime(); auto builder = lifetime.make_state<SparseIdsSliceBuilder>( aroundId, limitBefore, limitAfter); builder->insufficientAround( ) | rpl::start_with_next([=]( const SparseIdsSliceBuilder::AroundData &data) { requestMore(data, query, listData); }, lifetime); auto pushNextSnapshot = [=] { consumer.put_next(builder->snapshot()); }; listData->list.sliceUpdated( ) | rpl::filter([=](const SliceUpdate &update) { return builder->applyUpdate(update); }) | rpl::start_with_next(pushNextSnapshot, lifetime); Auth().data().itemRemoved( ) | rpl::filter([=](not_null<const HistoryItem*> item) { return (item->history()->peer->id == peerId); }) | rpl::filter([=](not_null<const HistoryItem*> item) { return builder->removeOne(item->id); }) | rpl::start_with_next(pushNextSnapshot, lifetime); Auth().data().historyCleared( ) | rpl::filter([=](not_null<const History*> history) { return (history->peer->id == peerId); }) | rpl::filter([=] { return builder->removeAll(); }) | rpl::start_with_next(pushNextSnapshot, lifetime); using Result = Storage::SparseIdsListResult; listData->list.query(Storage::SparseIdsListQuery( aroundId, limitBefore, limitAfter )) | rpl::filter([=](const Result &result) { return builder->applyInitial(result); }) | rpl::start_with_next_done( pushNextSnapshot, [=] { builder->checkInsufficient(); }, lifetime); return lifetime; }; }
Auth AuthenticationTable::getAuthForDb( const std::string& dbname ) const { return mapFindWithDefault( _dbs, dbname, Auth() ); }
rpl::producer<SparseIdsSlice> SharedMediaViewer( Storage::SharedMediaKey key, int limitBefore, int limitAfter) { Expects(IsServerMsgId(key.messageId) || (key.messageId == 0)); Expects((key.messageId != 0) || (limitBefore == 0 && limitAfter == 0)); return [=](auto consumer) { auto lifetime = rpl::lifetime(); auto builder = lifetime.make_state<SparseIdsSliceBuilder>( key.messageId, limitBefore, limitAfter); auto requestMediaAround = [ peer = App::peer(key.peerId), type = key.type ](const SparseIdsSliceBuilder::AroundData &data) { Auth().api().requestSharedMedia( peer, type, data.aroundId, data.direction); }; builder->insufficientAround( ) | rpl::start_with_next(requestMediaAround, lifetime); auto pushNextSnapshot = [=] { consumer.put_next(builder->snapshot()); }; using SliceUpdate = Storage::SharedMediaSliceUpdate; Auth().storage().sharedMediaSliceUpdated( ) | rpl::filter([=](const SliceUpdate &update) { return (update.peerId == key.peerId) && (update.type == key.type); }) | rpl::filter([=](const SliceUpdate &update) { return builder->applyUpdate(update.data); }) | rpl::start_with_next(pushNextSnapshot, lifetime); using OneRemoved = Storage::SharedMediaRemoveOne; Auth().storage().sharedMediaOneRemoved( ) | rpl::filter([=](const OneRemoved &update) { return (update.peerId == key.peerId) && update.types.test(key.type); }) | rpl::filter([=](const OneRemoved &update) { return builder->removeOne(update.messageId); }) | rpl::start_with_next(pushNextSnapshot, lifetime); using AllRemoved = Storage::SharedMediaRemoveAll; Auth().storage().sharedMediaAllRemoved( ) | rpl::filter([=](const AllRemoved &update) { return (update.peerId == key.peerId); }) | rpl::filter([=] { return builder->removeAll(); }) | rpl::start_with_next(pushNextSnapshot, lifetime); using InvalidateBottom = Storage::SharedMediaInvalidateBottom; Auth().storage().sharedMediaBottomInvalidated( ) | rpl::filter([=](const InvalidateBottom &update) { return (update.peerId == key.peerId); }) | rpl::filter([=] { return builder->invalidateBottom(); }) | rpl::start_with_next(pushNextSnapshot, lifetime); using Result = Storage::SharedMediaResult; Auth().storage().query(Storage::SharedMediaQuery( key, limitBefore, limitAfter )) | rpl::filter([=](const Result &result) { return builder->applyInitial(result); }) | rpl::start_with_next_done( pushNextSnapshot, [=] { builder->checkInsufficient(); }, lifetime); return lifetime; }; }
bool EventFilter::mainWindowEvent(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam, LRESULT *result) { using ShadowsChange = MainWindow::ShadowsChange; if (auto tbCreatedMsgId = Platform::MainWindow::TaskbarCreatedMsgId()) { if (msg == tbCreatedMsgId) { Platform::MainWindow::TaskbarCreated(); } } switch (msg) { case WM_TIMECHANGE: { if (AuthSession::Exists()) { Auth().checkAutoLockIn(100); } } return false; case WM_WTSSESSION_CHANGE: { if (wParam == WTS_SESSION_LOGOFF || wParam == WTS_SESSION_LOCK) { setSessionLoggedOff(true); } else if (wParam == WTS_SESSION_LOGON || wParam == WTS_SESSION_UNLOCK) { setSessionLoggedOff(false); } } return false; case WM_DESTROY: { App::quit(); } return false; case WM_ACTIVATE: { if (LOWORD(wParam) == WA_CLICKACTIVE) { App::wnd()->setInactivePress(true); } if (LOWORD(wParam) != WA_INACTIVE) { App::wnd()->shadowsActivate(); } else { App::wnd()->shadowsDeactivate(); } if (Global::started()) { App::wnd()->update(); } } return false; case WM_NCPAINT: { if (QSysInfo::WindowsVersion >= QSysInfo::WV_WINDOWS8) return false; if (result) *result = 0; } return true; case WM_NCCALCSIZE: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(hWnd, &wp) && wp.showCmd == SW_SHOWMAXIMIZED) { LPNCCALCSIZE_PARAMS params = (LPNCCALCSIZE_PARAMS)lParam; LPRECT r = (wParam == TRUE) ? ¶ms->rgrc[0] : (LPRECT)lParam; HMONITOR hMonitor = MonitorFromPoint({ (r->left + r->right) / 2, (r->top + r->bottom) / 2 }, MONITOR_DEFAULTTONEAREST); if (hMonitor) { MONITORINFO mi; mi.cbSize = sizeof(mi); if (GetMonitorInfo(hMonitor, &mi)) { *r = mi.rcWork; } } } if (result) *result = 0; return true; } case WM_NCACTIVATE: { if (IsCompositionEnabled()) { const auto res = DefWindowProc(hWnd, msg, wParam, -1); if (result) *result = res; } else { // Thanks https://github.com/melak47/BorderlessWindow if (result) *result = 1; } } return true; case WM_WINDOWPOSCHANGING: case WM_WINDOWPOSCHANGED: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(hWnd, &wp) && (wp.showCmd == SW_SHOWMAXIMIZED || wp.showCmd == SW_SHOWMINIMIZED)) { App::wnd()->shadowsUpdate(ShadowsChange::Hidden); } else { App::wnd()->shadowsUpdate(ShadowsChange::Moved | ShadowsChange::Resized, (WINDOWPOS*)lParam); } } return false; case WM_SIZE: { if (App::wnd()) { if (wParam == SIZE_MAXIMIZED || wParam == SIZE_RESTORED || wParam == SIZE_MINIMIZED) { if (wParam != SIZE_RESTORED || App::wnd()->windowState() != Qt::WindowNoState) { Qt::WindowState state = Qt::WindowNoState; if (wParam == SIZE_MAXIMIZED) { state = Qt::WindowMaximized; } else if (wParam == SIZE_MINIMIZED) { state = Qt::WindowMinimized; } emit App::wnd()->windowHandle()->windowStateChanged(state); } else { App::wnd()->positionUpdated(); } App::wnd()->psUpdateMargins(); MainWindow::ShadowsChanges changes = (wParam == SIZE_MINIMIZED || wParam == SIZE_MAXIMIZED) ? ShadowsChange::Hidden : (ShadowsChange::Resized | ShadowsChange::Shown); App::wnd()->shadowsUpdate(changes); } } } return false; case WM_SHOWWINDOW: { LONG style = GetWindowLong(hWnd, GWL_STYLE); auto changes = ShadowsChange::Resized | ((wParam && !(style & (WS_MAXIMIZE | WS_MINIMIZE))) ? ShadowsChange::Shown : ShadowsChange::Hidden); App::wnd()->shadowsUpdate(changes); } return false; case WM_MOVE: { App::wnd()->shadowsUpdate(ShadowsChange::Moved); App::wnd()->positionUpdated(); } return false; case WM_NCHITTEST: { if (!result) return false; POINTS p = MAKEPOINTS(lParam); RECT r; GetWindowRect(hWnd, &r); auto res = App::wnd()->hitTest(QPoint(p.x - r.left + App::wnd()->deltaLeft(), p.y - r.top + App::wnd()->deltaTop())); switch (res) { case Window::HitTestResult::Client: case Window::HitTestResult::SysButton: *result = HTCLIENT; break; case Window::HitTestResult::Caption: *result = HTCAPTION; break; case Window::HitTestResult::Top: *result = HTTOP; break; case Window::HitTestResult::TopRight: *result = HTTOPRIGHT; break; case Window::HitTestResult::Right: *result = HTRIGHT; break; case Window::HitTestResult::BottomRight: *result = HTBOTTOMRIGHT; break; case Window::HitTestResult::Bottom: *result = HTBOTTOM; break; case Window::HitTestResult::BottomLeft: *result = HTBOTTOMLEFT; break; case Window::HitTestResult::Left: *result = HTLEFT; break; case Window::HitTestResult::TopLeft: *result = HTTOPLEFT; break; case Window::HitTestResult::None: default: *result = HTTRANSPARENT; break; }; } return true; case WM_NCRBUTTONUP: { SendMessage(hWnd, WM_SYSCOMMAND, SC_MOUSEMENU, lParam); } return true; case WM_SYSCOMMAND: { if (wParam == SC_MOUSEMENU) { POINTS p = MAKEPOINTS(lParam); App::wnd()->updateSystemMenu(App::wnd()->windowHandle()->windowState()); TrackPopupMenu(App::wnd()->psMenu(), TPM_LEFTALIGN | TPM_TOPALIGN | TPM_LEFTBUTTON, p.x, p.y, 0, hWnd, 0); } } return false; case WM_COMMAND: { if (HIWORD(wParam)) return false; int cmd = LOWORD(wParam); switch (cmd) { case SC_CLOSE: App::wnd()->close(); return true; case SC_MINIMIZE: App::wnd()->setWindowState(Qt::WindowMinimized); return true; case SC_MAXIMIZE: App::wnd()->setWindowState(Qt::WindowMaximized); return true; case SC_RESTORE: App::wnd()->setWindowState(Qt::WindowNoState); return true; } } return true; } return false; }
bool AttachmentTest(CSocket* socket,CDlgMain* dlg,char* buffer,CDlgSettings* dlg2) { bool filtering = false; dlg->console+=_T("\r\n*Starting Attachment filtering Test."); dlg->UpdateData(FALSE); ScrollToBottom(dlg); if(dlg2->auth_use) { if(!Auth(socket,dlg,buffer,dlg2->auth_use,dlg2->set_authuser,dlg2->set_authpass)) { dlg->result_attachm = _T("?"); dlg->MessageBox(_T("Couldn't test attachment filtering because provided authentication data are incorrect")); return false; } } else { Send(socket,dlg,"HELO mozilla"); Receive(socket,dlg,buffer); } CString temp, temp2; char* msg; temp = dlg2->set_attach_path; temp+= _T("/*.*"); char* path = StringToChar(temp); CFileFind Finder; BOOL found1 = Finder.FindFile(temp); DWORD Error1 = GetLastError(); DWORD Error2 = -1; BOOL found2 = TRUE; CString sName = _T("(not found)"); int check = 0; CString sEncoded; char* encoded; if(found1) { while(found2) { check++; found2 = Finder.FindNextFile(); Error2 = GetLastError(); if(!Finder.IsDirectory()) { sName = Finder.GetFileName(); FILE* pFile; long fSize; char* fbuffer; size_t fresult; temp = dlg2->set_attach_path; temp+= _T("/"); temp+=sName; msg = StringToChar(temp); pFile = fopen((const char*)msg,"rb"); if(!pFile) { dlg->result_attachm = _T("?"); dlg->UpdateData(FALSE); ScrollToBottom(dlg); dlg->MessageBox(_T("Attachment filtering test error: Unable to open file")); break; } else { fseek(pFile , 0 , SEEK_END); fSize = ftell(pFile); rewind(pFile); fbuffer = new char[fSize]; fresult = fread(fbuffer,1,fSize,pFile); fclose (pFile); sEncoded = Base64Encode((unsigned char*)fbuffer,fSize); free (fbuffer); Send(socket,dlg,"RSET"); Receive(socket,dlg,buffer); temp = _T("MAIL FROM:<"); temp+=dlg2->set_attach_from; temp+=_T(">"); msg = StringToChar(temp); Send(socket,dlg,msg); Receive(socket,dlg,buffer); if(strcmp((const char*)MidStr(buffer,0,3),"250")!=0) { dlg->result_attachm = _T("?"); dlg->UpdateData(FALSE); dlg->MessageBox(_T("Attachment filtering test error: Bad FROM field")); break; } else // [FROM] OK { temp = _T("RCPT TO:<"); temp+=dlg2->set_attach_to; temp+=_T(">"); msg = StringToChar(temp); Send(socket,dlg,msg); Receive(socket,dlg,buffer); if(strcmp((const char*)MidStr(buffer,0,3),"250")!=0) { dlg->result_attachm = _T("?"); dlg->UpdateData(FALSE); dlg->MessageBox(_T("Attachment filtering test error: Bad RCPT TO field")); break; } else // [TO] OK { Send(socket,dlg,"DATA"); Receive(socket,dlg,buffer); Send(socket,dlg,"MIME-Version: 1.0"); temp = _T("From: "); temp+=dlg2->set_attach_from; msg = StringToChar(temp); Send(socket,dlg,msg); temp = _T("To: "); temp+=dlg2->set_attach_to; msg = StringToChar(temp); Send(socket,dlg,msg); temp = _T("Subject: Check Nr "); temp2.Format(_T("%d"),check); temp+=temp2; temp+= _T(" with \""); temp+=sName; temp+= _T("\""); msg = StringToChar(temp); Send(socket,dlg,msg); Send(socket,dlg,"Content-Type: multipart/mixed; boundary=\"xxxHELLOxWORLDxxx\""); Send(socket,dlg,""); Send(socket,dlg,"I am MIME message."); Send(socket,dlg,"--xxxHELLOxWORLDxxx"); Send(socket,dlg,"Content-type: text/plain;"); Send(socket,dlg,""); Send(socket,dlg,"SMTP Tool test."); Send(socket,dlg,"--xxxHELLOxWORLDxxx"); Send(socket,dlg,"Content-Type: application/octet-stream"); Send(socket,dlg,"Content-Transfer-Encoding: base64"); temp = _T("Content-Disposition: attachment; filename=\""); temp+=sName; temp+= _T("\""); msg = StringToChar(temp); Send(socket,dlg,msg); Send(socket,dlg,""); // data encoded = StringToChar(sEncoded); Send(socket,dlg,encoded); delete encoded; Send(socket,dlg,"--xxxHELLOxWORLDxxx--"); Send(socket,dlg,""); Send(socket,dlg,"."); Receive(socket,dlg,buffer); filtering = (strcmp((const char*)MidStr(buffer,0,3),"250")!=0); if(filtering) { //break; } if((dlg2->set_attach_delay!=_T(""))||(dlg2->set_attach_delay!=_T("0"))) { temp = _T("\r\nWaiting "); int ag = _wtoi(dlg2->set_attach_delay); temp2.Format(_T("%d"),ag); temp+=temp2; temp+= _T(" seconds..."); dlg->console+=temp; dlg->UpdateData(FALSE); ScrollToBottom(dlg); Sleep(ag*1000); } } } } } } } if(dlg->result_attachm!=_T("?")) dlg->result_attachm = filtering?_T("YES"):_T("NO"); Send(socket,dlg,"QUIT"); Receive(socket,dlg,buffer); return true; }
void PhotoData::download(Data::FileOrigin origin) { full->loadEvenCancelled(origin); Auth().data().notifyPhotoLayoutChanged(this); }