diff --git a/Telegram/SourceFiles/apiwrap.cpp b/Telegram/SourceFiles/apiwrap.cpp index b52302197..9120f9caf 100644 --- a/Telegram/SourceFiles/apiwrap.cpp +++ b/Telegram/SourceFiles/apiwrap.cpp @@ -24,6 +24,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "core/core_cloud_password.h" #include "core/application.h" #include "base/openssl_help.h" +#include "base/unixtime.h" #include "observer_peer.h" #include "lang/lang_keys.h" #include "mainwindow.h" @@ -259,7 +260,7 @@ void ApiWrap::setupSupportMode() { _session->settings().supportChatsTimeSliceValue( ) | rpl::start_with_next([=](int seconds) { - _dialogsLoadTill = seconds ? std::max(unixtime() - seconds, 0) : 0; + _dialogsLoadTill = seconds ? std::max(base::unixtime::now() - seconds, 0) : 0; refreshDialogsLoadBlocked(); }, _session->lifetime()); } @@ -275,7 +276,7 @@ void ApiWrap::requestChangelog( } void ApiWrap::refreshProxyPromotion() { - const auto now = unixtime(); + const auto now = base::unixtime::now(); const auto next = (_proxyPromotionNextRequestTime != 0) ? _proxyPromotionNextRequestTime : now; @@ -300,7 +301,7 @@ void ApiWrap::refreshProxyPromotion() { _proxyPromotionKey = key; if (key.first.isEmpty() || !key.second) { proxyPromotionDone(MTP_help_proxyDataEmpty( - MTP_int(unixtime() + kProxyPromotionInterval))); + MTP_int(base::unixtime::now() + kProxyPromotionInterval))); return; } _proxyPromotionRequestId = request(MTPhelp_GetProxyData( @@ -309,7 +310,7 @@ void ApiWrap::refreshProxyPromotion() { proxyPromotionDone(result); }).fail([=](const RPCError &error) { _proxyPromotionRequestId = 0; - const auto now = unixtime(); + const auto now = base::unixtime::now(); const auto next = _proxyPromotionNextRequestTime = now + kProxyPromotionInterval; if (!_proxyPromotionTimer.isActive()) { @@ -328,7 +329,7 @@ void ApiWrap::proxyPromotionDone(const MTPhelp_ProxyData &proxy) { _proxyPromotionNextRequestTime = proxy.match([&](const auto &data) { return data.vexpires().v; }); - getProxyPromotionDelayed(unixtime(), _proxyPromotionNextRequestTime); + getProxyPromotionDelayed(base::unixtime::now(), _proxyPromotionNextRequestTime); proxy.match([&](const MTPDhelp_proxyDataEmpty &data) { _session->data().setProxyPromoted(nullptr); @@ -380,7 +381,7 @@ void ApiWrap::requestTermsUpdate() { _termsUpdateRequestId = 0; const auto requestNext = [&](auto &&data) { - const auto timeout = (data.vexpires().v - unixtime()); + const auto timeout = (data.vexpires().v - base::unixtime::now()); _termsUpdateSendAt = crl::now() + snap( timeout * crl::time(1000), kTermsUpdateTimeoutMin, @@ -966,7 +967,7 @@ void ApiWrap::requestMoreBlockedByDateDialogs() { const auto max = _session->settings().supportChatsTimeSlice(); _dialogsLoadTill = _dialogsLoadState->offsetDate ? (_dialogsLoadState->offsetDate - max) - : (unixtime() - max); + : (base::unixtime::now() - max); refreshDialogsLoadBlocked(); requestDialogs(); } @@ -2120,7 +2121,7 @@ void ApiWrap::saveStickerSets( order.push_back(setId); it->flags |= MTPDstickerSet::Flag::f_installed_date; if (!it->installDate) { - it->installDate = unixtime(); + it->installDate = base::unixtime::now(); } } } @@ -2215,7 +2216,7 @@ void ApiWrap::blockUser(not_null user) { if (_blockedUsersSlice) { _blockedUsersSlice->list.insert( _blockedUsersSlice->list.begin(), - { user, unixtime() }); + { user, base::unixtime::now() }); ++_blockedUsersSlice->total; _blockedUsersChanges.fire_copy(*_blockedUsersSlice); } @@ -2401,7 +2402,7 @@ void ApiWrap::handlePrivacyChange( } void ApiWrap::updatePrivacyLastSeens(const QVector &rules) { - const auto now = unixtime(); + const auto now = base::unixtime::now(); _session->data().enumerateUsers([&](UserData *user) { if (user->isSelf() || user->loadedStatus != PeerData::FullLoaded) { return; @@ -2734,7 +2735,7 @@ void ApiWrap::gotStickerSet(uint64 setId, const MTPmessages_StickerSet &result) void ApiWrap::requestWebPageDelayed(WebPageData *page) { if (page->pendingTill <= 0) return; _webPagesPending.insert(page, 0); - auto left = (page->pendingTill - unixtime()) * 1000; + auto left = (page->pendingTill - base::unixtime::now()) * 1000; if (!_webPagesTimer.isActive() || left <= _webPagesTimer.remainingTime()) { _webPagesTimer.callOnce((left < 0 ? 0 : left) + 1); } @@ -2759,7 +2760,7 @@ void ApiWrap::resolveWebPages() { MessageIdsByChannel idsByChannel; // temp_req_id = -index - 2 ids.reserve(_webPagesPending.size()); - int32 t = unixtime(), m = INT_MAX; + int32 t = base::unixtime::now(), m = INT_MAX; for (auto i = _webPagesPending.begin(); i != _webPagesPending.cend(); ++i) { if (i.value() > 0) continue; if (i.key()->pendingTill <= t) { @@ -3675,7 +3676,7 @@ void ApiWrap::applyUpdateNoPtsCheck(const MTPUpdate &update) { if (item->out() && item->history()->peer->isUser() && !App::main()->requestingDifference()) { - item->history()->peer->asUser()->madeAction(unixtime()); + item->history()->peer->asUser()->madeAction(base::unixtime::now()); } } } else { @@ -3705,7 +3706,7 @@ void ApiWrap::applyUpdateNoPtsCheck(const MTPUpdate &update) { history->outboxRead(d.vmax_id().v); if (!App::main()->requestingDifference()) { if (const auto user = history->peer->asUser()) { - user->madeAction(unixtime()); + user->madeAction(base::unixtime::now()); } } } @@ -4510,7 +4511,7 @@ void ApiWrap::forwardMessages( history->addNewForwarded( newId.msg, flags, - unixtime(), + base::unixtime::now(), messageFromId, messagePostAuthor, message); @@ -4599,7 +4600,7 @@ void ApiWrap::sendSharedContact( MTPMessageFwdHeader(), MTPint(), MTP_int(options.replyTo), - MTP_int(unixtime()), + MTP_int(base::unixtime::now()), MTP_string(), MTP_messageMediaContact( MTP_string(phone), @@ -4981,7 +4982,7 @@ void ApiWrap::sendMessage(MessageToSend &&message) { MTPMessageFwdHeader(), MTPint(), MTP_int(message.replyTo), - MTP_int(unixtime()), + MTP_int(base::unixtime::now()), msgText, media, MTPReplyMarkup(), @@ -5089,7 +5090,7 @@ void ApiWrap::sendInlineResult( auto messagePostAuthor = channelPost ? App::peerName(_session->user()) : QString(); - MTPint messageDate = MTP_int(unixtime()); + MTPint messageDate = MTP_int(base::unixtime::now()); UserId messageViaBotId = bot ? peerToUser(bot->id) : 0; MsgId messageId = newId.msg; @@ -5184,7 +5185,7 @@ void ApiWrap::sendExistingDocument( flags, 0, replyTo, - unixtime(), + base::unixtime::now(), messageFromId, messagePostAuthor, document, diff --git a/Telegram/SourceFiles/base/unixtime.cpp b/Telegram/SourceFiles/base/unixtime.cpp new file mode 100644 index 000000000..b4ef55eb1 --- /dev/null +++ b/Telegram/SourceFiles/base/unixtime.cpp @@ -0,0 +1,179 @@ +/* +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 "base/unixtime.h" + +#include "logs.h" + +#include +#include + +#ifdef Q_OS_WIN +#elif defined Q_OS_MAC +#include +#else +#include +#endif + +namespace base { +namespace unixtime { +namespace { + +std::atomic ValueUpdated/* = false*/; +std::atomic ValueShift/* = 0*/; +std::atomic HttpValueValid/* = false*/; +std::atomic HttpValueShift/* = 0*/; + +class MsgIdManager { +public: + MsgIdManager(); + + void update(); + [[nodiscard]] uint64 next(); + +private: + void initialize(); + + QReadWriteLock _lock; + uint64 _startId = 0; + std::atomic _incrementedPart = 0; + uint64 _startCounter = 0; + uint64 _randomPart = 0; + float64 _multiplier = 0.; + +}; + +MsgIdManager GlobalMsgIdManager; + +[[nodiscard]] float64 GetMultiplier() { + // 0xFFFF0000 instead of 0x100000000 to make msgId grow slightly slower, + // than unixtime and we had time to reconfigure. + +#ifdef Q_OS_WIN + LARGE_INTEGER li; + QueryPerformanceFrequency(&li); + return float64(0xFFFF0000L) / float64(li.QuadPart); +#elif defined Q_OS_MAC // Q_OS_WIN + mach_timebase_info_data_t tb = { 0, 0 }; + mach_timebase_info(&tb); + const auto frequency = (float64(tb.numer) / tb.denom) / 1000000.; + return frequency * (float64(0xFFFF0000L) / 1000.); +#else // Q_OS_MAC || Q_OS_WIN + return float64(0xFFFF0000L) / 1000000000.; +#endif // Q_OS_MAC || Q_OS_WIN +} + +[[nodiscard]] uint64 GetCounter() { +#ifdef Q_OS_WIN + LARGE_INTEGER li; + QueryPerformanceCounter(&li); + return li.QuadPart; +#elif defined Q_OS_MAC // Q_OS_WIN + return mach_absolute_time(); +#else // Q_OS_MAC || Q_OS_WIN + timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return 1000000000 * uint64(ts.tv_sec) + uint64(ts.tv_nsec); +#endif // Q_OS_MAC || Q_OS_WIN +} + +MsgIdManager::MsgIdManager() { + auto generator = std::mt19937(std::random_device()()); + auto distribution = std::uniform_int_distribution(); + _randomPart = distribution(generator); + _multiplier = GetMultiplier(); + initialize(); + + srand(uint32(_startCounter & 0xFFFFFFFFUL)); +} + +void MsgIdManager::update() { + QWriteLocker lock(&_lock); + initialize(); +} + +void MsgIdManager::initialize() { + _startCounter = GetCounter(); + _startId = ((uint64(uint32(now()))) << 32) | _randomPart; +} + +uint64 MsgIdManager::next() { + const auto counter = GetCounter(); + + QReadLocker lock(&_lock); + const auto delta = (counter - _startCounter); + const auto result = _startId + (uint64)floor(delta * _multiplier); + lock.unlock(); + + return (result & ~0x03L) + (_incrementedPart += 4); +} + +TimeId local() { + return (TimeId)time(nullptr); +} + +} // namespace + +TimeId now() { + return local() + ValueShift.load(); +} + +void update(TimeId now, bool force) { + if (force) { + DEBUG_LOG(("MTP Info: forcing client unixtime to %1" + ).arg(now)); + ValueUpdated = true; + } else { + auto expected = false; + if (!ValueUpdated.compare_exchange_strong(expected, true)) { + return; + } + DEBUG_LOG(("MTP Info: setting client unixtime to %1").arg(now)); + } + const auto shift = now + 1 - local(); + ValueShift = shift; + DEBUG_LOG(("MTP Info: now unixtimeDelta is %1").arg(shift)); + + HttpValueShift = 0; + HttpValueValid = false; + + GlobalMsgIdManager.update(); +} + +QDateTime parse(TimeId value) { + return (value > 0) + ? QDateTime::fromTime_t(value - ValueShift) + : QDateTime(); +} + +TimeId serialize(const QDateTime &date) { + return date.isNull() ? TimeId(0) : date.toTime_t() + ValueShift; +} + +bool http_valid() { + return HttpValueValid; +} + +TimeId http_now() { + return now() + HttpValueShift; +} + +void http_update(TimeId now) { + HttpValueShift = now - base::unixtime::now(); + HttpValueValid = true; +} + +void http_invalidate() { + HttpValueValid = false; +} + +uint64 mtproto_msg_id() { + return GlobalMsgIdManager.next(); +} + +} // namespace unixtime +} // namespace base diff --git a/Telegram/SourceFiles/base/unixtime.h b/Telegram/SourceFiles/base/unixtime.h new file mode 100644 index 000000000..9db64ed2a --- /dev/null +++ b/Telegram/SourceFiles/base/unixtime.h @@ -0,0 +1,33 @@ +/* +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 +*/ +#pragma once + +#include "base/basic_types.h" + +class QDateTime; + +namespace base { +namespace unixtime { + +// All functions are thread-safe. + +[[nodiscard]] TimeId now(); +void update(TimeId now, bool force = false); + +[[nodiscard]] QDateTime parse(TimeId value); +[[nodiscard]] TimeId serialize(const QDateTime &date); + +[[nodiscard]] bool http_valid(); +[[nodiscard]] TimeId http_now(); +void http_update(TimeId now); +void http_invalidate(); + +[[nodiscard]] uint64 mtproto_msg_id(); + +} // namespace unixtime +} // namespace base diff --git a/Telegram/SourceFiles/boxes/background_preview_box.cpp b/Telegram/SourceFiles/boxes/background_preview_box.cpp index 02852282f..bbd5355c3 100644 --- a/Telegram/SourceFiles/boxes/background_preview_box.cpp +++ b/Telegram/SourceFiles/boxes/background_preview_box.cpp @@ -21,6 +21,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_session.h" #include "data/data_user.h" #include "data/data_document.h" +#include "base/unixtime.h" #include "boxes/confirm_box.h" #include "boxes/background_preview_box.h" #include "styles/style_history.h" @@ -291,7 +292,7 @@ AdminLog::OwnedItem GenerateTextItem( flags, replyTo, viaBotId, - unixtime(), + base::unixtime::now(), out ? history->session().userId() : peerToUser(history->peer->id), QString(), TextWithEntities{ TextUtilities::Clean(text) }); diff --git a/Telegram/SourceFiles/boxes/confirm_box.cpp b/Telegram/SourceFiles/boxes/confirm_box.cpp index 4a407ecfb..19618f6a9 100644 --- a/Telegram/SourceFiles/boxes/confirm_box.cpp +++ b/Telegram/SourceFiles/boxes/confirm_box.cpp @@ -30,6 +30,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_channel.h" #include "data/data_chat.h" #include "data/data_user.h" +#include "base/unixtime.h" #include "auth_session.h" #include "observer_peer.h" @@ -620,7 +621,7 @@ auto DeleteMessagesBox::revokeText(not_null peer) const return std::nullopt; } - const auto now = unixtime(); + const auto now = base::unixtime::now(); const auto canRevoke = [&](HistoryItem * item) { return item->canDeleteForEveryone(now); }; diff --git a/Telegram/SourceFiles/boxes/peer_list_box.cpp b/Telegram/SourceFiles/boxes/peer_list_box.cpp index 0300b0987..83c923f2f 100644 --- a/Telegram/SourceFiles/boxes/peer_list_box.cpp +++ b/Telegram/SourceFiles/boxes/peer_list_box.cpp @@ -28,6 +28,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_peer_values.h" #include "data/data_chat.h" #include "data/data_session.h" +#include "base/unixtime.h" #include "window/themes/window_theme.h" auto PaintUserpicCallback( @@ -57,7 +58,7 @@ void PeerListBox::createMultiSelect() { Expects(_select == nullptr); auto entity = object_ptr( - this, + this, st::contactsMultiSelect, tr::lng_participant_filter()); _select.create(this, std::move(entity)); @@ -377,7 +378,7 @@ void PeerListRow::refreshStatus() { if (_isSavedMessagesChat) { setStatusText(tr::lng_saved_forward_here(tr::now)); } else { - auto time = unixtime(); + auto time = base::unixtime::now(); setStatusText(Data::OnlineText(user, time)); if (Data::OnlineTextActive(user, time)) { _statusType = StatusType::Online; diff --git a/Telegram/SourceFiles/boxes/peers/add_participants_box.cpp b/Telegram/SourceFiles/boxes/peers/add_participants_box.cpp index 193ae0921..18f6d4536 100644 --- a/Telegram/SourceFiles/boxes/peers/add_participants_box.cpp +++ b/Telegram/SourceFiles/boxes/peers/add_participants_box.cpp @@ -17,6 +17,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_folder.h" #include "history/history.h" #include "dialogs/dialogs_indexed_list.h" +#include "base/unixtime.h" #include "auth_session.h" #include "mainwidget.h" #include "mainwindow.h" @@ -575,7 +576,7 @@ void AddSpecialBoxController::editAdminDone( _editParticipantBox->closeBox(); } - const auto date = unixtime(); // Incorrect, but ignored. + const auto date = base::unixtime::now(); // Incorrect, but ignored. if (rights.c_chatAdminRights().vflags().v == 0) { _additional.applyParticipant(MTP_channelParticipant( MTP_int(user->bareId()), @@ -672,7 +673,7 @@ void AddSpecialBoxController::editRestrictedDone( _editParticipantBox->closeBox(); } - const auto date = unixtime(); // Incorrect, but ignored. + const auto date = base::unixtime::now(); // Incorrect, but ignored. if (rights.c_chatBannedRights().vflags().v == 0) { _additional.applyParticipant(MTP_channelParticipant( MTP_int(user->bareId()), diff --git a/Telegram/SourceFiles/boxes/peers/edit_participant_box.cpp b/Telegram/SourceFiles/boxes/peers/edit_participant_box.cpp index ec7164b37..abe56d344 100644 --- a/Telegram/SourceFiles/boxes/peers/edit_participant_box.cpp +++ b/Telegram/SourceFiles/boxes/peers/edit_participant_box.cpp @@ -31,6 +31,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_chat.h" #include "data/data_user.h" #include "core/core_cloud_password.h" +#include "base/unixtime.h" #include "apiwrap.h" #include "auth_session.h" #include "styles/style_boxes.h" @@ -203,7 +204,7 @@ void EditParticipantBox::Inner::paintEvent(QPaintEvent *e) { ? tr::lng_status_bot_reads_all : tr::lng_status_bot_not_reads_all)(tr::now); } - return Data::OnlineText(_user->onlineTill, unixtime()); + return Data::OnlineText(_user->onlineTill, base::unixtime::now()); }; p.setFont(st::contactsStatusFont); p.setPen(st::contactsStatusFg); @@ -678,7 +679,7 @@ void EditRestrictedBox::showRestrictUntil() { auto tomorrow = QDate::currentDate().addDays(1); auto highlighted = isUntilForever() ? tomorrow - : ParseDateTime(getRealUntilValue()).date(); + : base::unixtime::parse(getRealUntilValue()).date(); auto month = highlighted; _restrictUntilBox = Ui::show( Box( @@ -751,7 +752,8 @@ void EditRestrictedBox::createUntilVariants() { tr::lng_rights_chat_banned_custom_date( tr::now, lt_date, - langDayOfMonthFull(ParseDateTime(until).date()))); + langDayOfMonthFull( + base::unixtime::parse(until).date()))); } }; auto addCurrentVariant = [&](TimeId from, TimeId to) { @@ -766,7 +768,7 @@ void EditRestrictedBox::createUntilVariants() { }; addVariant(0, tr::lng_rights_chat_banned_forever(tr::now)); - auto now = unixtime(); + auto now = base::unixtime::now(); auto nextDay = now + kSecondsInDay; auto nextWeek = now + kSecondsInWeek; addCurrentVariant(0, nextDay); @@ -780,9 +782,9 @@ void EditRestrictedBox::createUntilVariants() { TimeId EditRestrictedBox::getRealUntilValue() const { Expects(_until != kUntilCustom); if (_until == kUntilOneDay) { - return unixtime() + kSecondsInDay; + return base::unixtime::now() + kSecondsInDay; } else if (_until == kUntilOneWeek) { - return unixtime() + kSecondsInWeek; + return base::unixtime::now() + kSecondsInWeek; } Assert(_until >= 0); return _until; diff --git a/Telegram/SourceFiles/boxes/peers/edit_participants_box.cpp b/Telegram/SourceFiles/boxes/peers/edit_participants_box.cpp index 4bc65faee..15404e7e9 100644 --- a/Telegram/SourceFiles/boxes/peers/edit_participants_box.cpp +++ b/Telegram/SourceFiles/boxes/peers/edit_participants_box.cpp @@ -23,6 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_channel.h" #include "data/data_chat.h" #include "data/data_user.h" +#include "base/unixtime.h" #include "ui/widgets/popup_menu.h" #include "window/window_session_controller.h" #include "history/history.h" @@ -671,7 +672,7 @@ void ParticipantsOnlineSorter::sort() { _onlineCount = 0; return; } - const auto now = unixtime(); + const auto now = base::unixtime::now(); _delegate->peerListSortRows([&]( const PeerListRow &a, const PeerListRow &b) { @@ -686,7 +687,7 @@ rpl::producer ParticipantsOnlineSorter::onlineCountValue() const { } void ParticipantsOnlineSorter::refreshOnlineCount() { - const auto now = unixtime(); + const auto now = base::unixtime::now(); auto left = 0, right = _delegate->peerListFullRowsCount(); while (right > left) { const auto middle = (left + right) / 2; @@ -1441,7 +1442,7 @@ void ParticipantsBoxController::editAdminDone( _editParticipantBox->closeBox(); } - const auto date = unixtime(); // Incorrect, but ignored. + const auto date = base::unixtime::now(); // Incorrect, but ignored. if (rights.c_chatAdminRights().vflags().v == 0) { _additional.applyParticipant(MTP_channelParticipant( MTP_int(user->bareId()), @@ -1509,7 +1510,7 @@ void ParticipantsBoxController::editRestrictedDone( _editParticipantBox->closeBox(); } - const auto date = unixtime(); // Incorrect, but ignored. + const auto date = base::unixtime::now(); // Incorrect, but ignored. if (rights.c_chatBannedRights().vflags().v == 0) { _additional.applyParticipant(MTP_channelParticipant( MTP_int(user->bareId()), diff --git a/Telegram/SourceFiles/boxes/sessions_box.cpp b/Telegram/SourceFiles/boxes/sessions_box.cpp index 787572896..69fa65233 100644 --- a/Telegram/SourceFiles/boxes/sessions_box.cpp +++ b/Telegram/SourceFiles/boxes/sessions_box.cpp @@ -13,6 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mainwindow.h" #include "auth_session.h" #include "data/data_session.h" +#include "base/unixtime.h" #include "boxes/confirm_box.h" #include "info/profile/info_profile_button.h" #include "settings/settings_common.h" @@ -229,7 +230,7 @@ SessionsBox::Entry SessionsBox::ParseEntry(const MTPDauthorization &data) { result.activeWidth = st::sessionWhenFont->width(tr::lng_status_online(tr::now)); } else { const auto now = QDateTime::currentDateTime(); - const auto lastTime = ParseDateTime(result.activeTime); + const auto lastTime = base::unixtime::parse(result.activeTime); const auto nowDate = now.date(); const auto lastDate = lastTime.date(); if (lastDate == nowDate) { diff --git a/Telegram/SourceFiles/boxes/sticker_set_box.cpp b/Telegram/SourceFiles/boxes/sticker_set_box.cpp index b8e602bb8..27c47d69b 100644 --- a/Telegram/SourceFiles/boxes/sticker_set_box.cpp +++ b/Telegram/SourceFiles/boxes/sticker_set_box.cpp @@ -24,6 +24,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lottie/lottie_multi_player.h" #include "lottie/lottie_animation.h" #include "window/window_session_controller.h" +#include "base/unixtime.h" #include "auth_session.h" #include "apiwrap.h" #include "mainwidget.h" @@ -342,7 +343,7 @@ void StickerSetBox::Inner::installDone( Auth().data().archivedStickerSetsOrderRef().removeAt(index); } } - _setInstallDate = unixtime(); + _setInstallDate = base::unixtime::now(); _setFlags &= ~MTPDstickerSet::Flag::f_archived; _setFlags |= MTPDstickerSet::Flag::f_installed_date; auto it = sets.find(_setId); diff --git a/Telegram/SourceFiles/calls/calls_instance.cpp b/Telegram/SourceFiles/calls/calls_instance.cpp index 1577dec08..3f1fbedc5 100644 --- a/Telegram/SourceFiles/calls/calls_instance.cpp +++ b/Telegram/SourceFiles/calls/calls_instance.cpp @@ -19,6 +19,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_session.h" #include "media/audio/media_audio_track.h" #include "platform/platform_specific.h" +#include "base/unixtime.h" #include "mainwidget.h" #include "boxes/rate_call_box.h" @@ -249,7 +250,8 @@ void Instance::handleCallUpdate(const MTPPhoneCall &call) { MTP_phoneCallDiscardReasonBusy(), MTP_long(0) )).send(); - } else if (phoneCall.vdate().v + (Global::CallRingTimeoutMs() / 1000) < unixtime()) { + } else if (phoneCall.vdate().v + (Global::CallRingTimeoutMs() / 1000) + < base::unixtime::now()) { LOG(("Ignoring too old call.")); } else { createCall(user, Call::Type::Incoming); diff --git a/Telegram/SourceFiles/chat_helpers/field_autocomplete.cpp b/Telegram/SourceFiles/chat_helpers/field_autocomplete.cpp index e9558b71a..eebbb1ff0 100644 --- a/Telegram/SourceFiles/chat_helpers/field_autocomplete.cpp +++ b/Telegram/SourceFiles/chat_helpers/field_autocomplete.cpp @@ -20,6 +20,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/image/image.h" #include "auth_session.h" #include "chat_helpers/stickers.h" +#include "base/unixtime.h" #include "styles/style_history.h" #include "styles/style_widgets.h" #include "styles/style_chat_helpers.h" @@ -183,7 +184,7 @@ internal::StickerRows FieldAutocomplete::getStickerSuggestions() { } void FieldAutocomplete::updateFiltered(bool resetScroll) { - int32 now = unixtime(), recentInlineBots = 0; + int32 now = base::unixtime::now(), recentInlineBots = 0; internal::MentionRows mrows; internal::HashtagRows hrows; internal::BotCommandRows brows; diff --git a/Telegram/SourceFiles/chat_helpers/stickers.cpp b/Telegram/SourceFiles/chat_helpers/stickers.cpp index 5aa2109b4..ec434abfd 100644 --- a/Telegram/SourceFiles/chat_helpers/stickers.cpp +++ b/Telegram/SourceFiles/chat_helpers/stickers.cpp @@ -19,6 +19,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mainwindow.h" #include "ui/toast/toast.h" #include "ui/emoji_config.h" +#include "base/unixtime.h" #include "lottie/lottie_single_player.h" #include "lottie/lottie_multi_player.h" #include "styles/style_chat_helpers.h" @@ -126,7 +127,7 @@ void InstallLocally(uint64 setId) { auto flags = it->flags; it->flags &= ~(MTPDstickerSet::Flag::f_archived | MTPDstickerSet_ClientFlag::f_unread); it->flags |= MTPDstickerSet::Flag::f_installed_date; - it->installDate = unixtime(); + it->installDate = base::unixtime::now(); auto changedFlags = flags ^ it->flags; auto &order = Auth().data().stickerSetsOrderRef(); @@ -922,7 +923,7 @@ Set *FeedSet(const MTPDstickerSet &set) { it->flags = set.vflags().v | clientFlags; const auto installDate = set.vinstalled_date(); it->installDate = installDate - ? (installDate->v ? installDate->v : unixtime()) + ? (installDate->v ? installDate->v : base::unixtime::now()) : TimeId(0); it->thumbnail = thumbnail; if (it->count != set.vcount().v diff --git a/Telegram/SourceFiles/core/application.cpp b/Telegram/SourceFiles/core/application.cpp index 743d20467..a351e1f7a 100644 --- a/Telegram/SourceFiles/core/application.cpp +++ b/Telegram/SourceFiles/core/application.cpp @@ -13,6 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_user.h" #include "base/timer.h" #include "base/concurrent_timer.h" +#include "base/unixtime.h" #include "core/update_checker.h" #include "core/shortcuts.h" #include "core/sandbox.h" @@ -692,6 +693,7 @@ void Application::checkLocalTime() { if (crl::adjust_time()) { base::Timer::Adjust(); base::ConcurrentTimerEnvironment::Adjust(); + base::unixtime::http_invalidate(); if (App::main()) App::main()->checkLastUpdate(true); } else { if (App::main()) App::main()->checkLastUpdate(false); diff --git a/Telegram/SourceFiles/core/file_utilities.cpp b/Telegram/SourceFiles/core/file_utilities.cpp index 2a58a5309..71c200777 100644 --- a/Telegram/SourceFiles/core/file_utilities.cpp +++ b/Telegram/SourceFiles/core/file_utilities.cpp @@ -10,6 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "storage/localstorage.h" #include "platform/platform_file_utilities.h" #include "core/application.h" +#include "base/unixtime.h" #include "mainwindow.h" bool filedialogGetSaveFile( @@ -62,7 +63,7 @@ QString filedialogDefaultName( QString base; if (fileTime) { - const auto date = ParseDateTime(fileTime); + const auto date = base::unixtime::parse(fileTime); base = prefix + date.toString("_yyyy-MM-dd_HH-mm-ss"); } else { struct tm tm; diff --git a/Telegram/SourceFiles/core/launcher.cpp b/Telegram/SourceFiles/core/launcher.cpp index 1b8c4795e..9237e629d 100644 --- a/Telegram/SourceFiles/core/launcher.cpp +++ b/Telegram/SourceFiles/core/launcher.cpp @@ -118,8 +118,10 @@ void ComputeInstallationTag() { file.close(); } if (!InstallationTag) { + auto generator = std::mt19937(std::random_device()()); + auto distribution = std::uniform_int_distribution(); do { - memsetrnd_bad(InstallationTag); + InstallationTag = distribution(generator); } while (!InstallationTag); if (file.open(QIODevice::WriteOnly)) { diff --git a/Telegram/SourceFiles/core/update_checker.cpp b/Telegram/SourceFiles/core/update_checker.cpp index fe025f0cd..800f7824c 100644 --- a/Telegram/SourceFiles/core/update_checker.cpp +++ b/Telegram/SourceFiles/core/update_checker.cpp @@ -10,6 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "platform/platform_info.h" #include "base/timer.h" #include "base/bytes.h" +#include "base/unixtime.h" #include "storage/localstorage.h" #include "core/application.h" #include "mainwindow.h" @@ -634,7 +635,7 @@ void HttpChecker::gotResponse() { return; } - cSetLastUpdateCheck(unixtime()); + cSetLastUpdateCheck(base::unixtime::now()); const auto response = _reply->readAll(); clearSentRequest(); @@ -1134,7 +1135,7 @@ void Updater::handleReady() { stop(); _action = Action::Ready; if (!App::quitting()) { - cSetLastUpdateCheck(unixtime()); + cSetLastUpdateCheck(base::unixtime::now()); Local::writeSettings(); } } @@ -1162,7 +1163,7 @@ void Updater::handleProgress() { void Updater::scheduleNext() { stop(); if (!App::quitting()) { - cSetLastUpdateCheck(unixtime()); + cSetLastUpdateCheck(base::unixtime::now()); Local::writeSettings(); start(true); } @@ -1208,7 +1209,7 @@ void Updater::start(bool forceWait) { const auto updateInSecs = cLastUpdateCheck() + constDelay + int(rand() % randDelay) - - unixtime(); + - base::unixtime::now(); auto sendRequest = (updateInSecs <= 0) || (updateInSecs > constDelay + randDelay); if (!sendRequest && !forceWait) { diff --git a/Telegram/SourceFiles/core/utils.cpp b/Telegram/SourceFiles/core/utils.cpp index fa4828ab0..5e2ed45af 100644 --- a/Telegram/SourceFiles/core/utils.cpp +++ b/Telegram/SourceFiles/core/utils.cpp @@ -56,35 +56,10 @@ static_assert(sizeof(MTPdouble) == 8, "Basic types size check failed"); static_assert(sizeof(int) >= 4, "Basic types size check failed"); -// Unixtime functions - namespace { std::atomic GlobalAtomicRequestId = 0; -QReadWriteLock unixtimeLock; -volatile int32 unixtimeDelta = 0; -volatile bool unixtimeWasSet = false; -volatile uint64 _msgIdStart, _msgIdLocal = 0, _msgIdMsStart; - -void _initMsgIdConstants() { -#ifdef Q_OS_WIN - LARGE_INTEGER li; - QueryPerformanceCounter(&li); - _msgIdMsStart = li.QuadPart; -#elif defined Q_OS_MAC - _msgIdMsStart = mach_absolute_time(); -#else - timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - _msgIdMsStart = 1000000000 * uint64(ts.tv_sec) + uint64(ts.tv_nsec); -#endif - - uint32 msgIdRand; - memset_rand(&msgIdRand, sizeof(uint32)); - _msgIdStart = (((uint64)((uint32)unixtime()) << 32) | (uint64)msgIdRand); -} - [[nodiscard]] bool IsHexMtprotoPassword(const QString &password) { const auto size = password.size(); if (size < 32 || size % 2 == 1) { @@ -208,58 +183,6 @@ void _initMsgIdConstants() { } // namespace -TimeId LocalUnixtime() { - return (TimeId)time(nullptr); -} - -void unixtimeInit() { - { - QWriteLocker locker(&unixtimeLock); - unixtimeWasSet = false; - unixtimeDelta = 0; - } - _initMsgIdConstants(); -} - -void unixtimeSet(int32 serverTime, bool force) { - { - QWriteLocker locker(&unixtimeLock); - if (force) { - DEBUG_LOG(("MTP Info: forced setting client unixtime to %1").arg(serverTime)); - } else { - if (unixtimeWasSet) return; - DEBUG_LOG(("MTP Info: setting client unixtime to %1").arg(serverTime)); - } - unixtimeWasSet = true; - unixtimeDelta = serverTime + 1 - LocalUnixtime(); - DEBUG_LOG(("MTP Info: now unixtimeDelta is %1").arg(unixtimeDelta)); - } - _initMsgIdConstants(); -} - -TimeId unixtime() { - auto result = LocalUnixtime(); - - QReadLocker locker(&unixtimeLock); - return result + unixtimeDelta; -} - -QDateTime ParseDateTime(TimeId serverTime) { - if (serverTime <= 0) { - return QDateTime(); - } - QReadLocker locker(&unixtimeLock); - return QDateTime::fromTime_t(serverTime - unixtimeDelta); -} - -TimeId ServerTimeFromParsed(const QDateTime &date) { - if (date.isNull()) { - return TimeId(0); - } - QReadLocker locker(&unixtimeLock); - return date.toTime_t() + unixtimeDelta; -} - // Precise timing functions / rand init struct CRYPTO_dynlock_value { @@ -320,38 +243,6 @@ namespace { } return 0; } - - float64 _msgIdCoef; - class _MsStarter { - public: - _MsStarter() { -#ifdef Q_OS_WIN - LARGE_INTEGER li; - QueryPerformanceFrequency(&li); - - // 0xFFFF0000L istead of 0x100000000L to make msgId grow slightly slower, than unixtime and we had time to reconfigure - _msgIdCoef = float64(0xFFFF0000L) / float64(li.QuadPart); - - QueryPerformanceCounter(&li); - const auto seed = li.QuadPart; -#elif defined Q_OS_MAC - mach_timebase_info_data_t tb = { 0, 0 }; - mach_timebase_info(&tb); - const auto freq = (float64(tb.numer) / tb.denom) / 1000000.; - _msgIdCoef = freq * (float64(0xFFFF0000L) / 1000.); - - const auto seed = mach_absolute_time(); -#else - _msgIdCoef = float64(0xFFFF0000L) / 1000000000.; - - timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - const auto seed = 1000LL * static_cast(ts.tv_sec) + (static_cast(ts.tv_nsec) / 1000000LL); -#endif - srand((uint32)(seed & 0xFFFFFFFFL)); - } - }; - _MsStarter _msStarter; } bool ProxyData::valid() const { @@ -536,26 +427,6 @@ namespace ThirdParty { } } -uint64 msgid() { -#ifdef Q_OS_WIN - LARGE_INTEGER li; - QueryPerformanceCounter(&li); - uint64 result = _msgIdStart + (uint64)floor((li.QuadPart - _msgIdMsStart) * _msgIdCoef); -#elif defined Q_OS_MAC - uint64 msCount = mach_absolute_time(); - uint64 result = _msgIdStart + (uint64)floor((msCount - _msgIdMsStart) * _msgIdCoef); -#else - timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - uint64 msCount = 1000000000 * uint64(ts.tv_sec) + uint64(ts.tv_nsec); - uint64 result = _msgIdStart + (uint64)floor((msCount - _msgIdMsStart) * _msgIdCoef); -#endif - - result &= ~0x03L; - - return result + (_msgIdLocal += 4); -} - int GetNextRequestId() { const auto result = ++GlobalAtomicRequestId; if (result == std::numeric_limits::max() / 2) { diff --git a/Telegram/SourceFiles/core/utils.h b/Telegram/SourceFiles/core/utils.h index eb72300d1..947530bd2 100644 --- a/Telegram/SourceFiles/core/utils.h +++ b/Telegram/SourceFiles/core/utils.h @@ -95,15 +95,8 @@ inline QByteArray str_const_toByteArray(const str_const &str) { return QByteArray::fromRawData(str.c_str(), str.size()); } -void unixtimeInit(); -void unixtimeSet(TimeId serverTime, bool force = false); -TimeId unixtime(); -uint64 msgid(); int GetNextRequestId(); -QDateTime ParseDateTime(TimeId serverTime); -TimeId ServerTimeFromParsed(const QDateTime &date); - inline void mylocaltime(struct tm * _Tm, const time_t * _Time) { #ifdef Q_OS_WIN localtime_s(_Tm, _Time); @@ -183,17 +176,6 @@ T rand_value() { return result; } -inline void memset_rand_bad(void *data, uint32 len) { - for (uchar *i = reinterpret_cast(data), *e = i + len; i != e; ++i) { - *i = uchar(rand() & 0xFF); - } -} - -template -inline void memsetrnd_bad(T &value) { - memset_rand_bad(&value, sizeof(value)); -} - class ReadLockerAttempt { public: ReadLockerAttempt(not_null lock) : _lock(lock), _locked(_lock->tryLockForRead()) { diff --git a/Telegram/SourceFiles/data/data_notify_settings.cpp b/Telegram/SourceFiles/data/data_notify_settings.cpp index 695109068..a1e3b95a0 100644 --- a/Telegram/SourceFiles/data/data_notify_settings.cpp +++ b/Telegram/SourceFiles/data/data_notify_settings.cpp @@ -7,6 +7,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL */ #include "data/data_notify_settings.h" +#include "base/unixtime.h" + namespace Data { namespace { @@ -71,7 +73,7 @@ bool NotifySettingsValue::change(const MTPDpeerNotifySettings &data) { bool NotifySettingsValue::change( std::optional muteForSeconds, std::optional silentPosts) { - const auto now = unixtime(); + const auto now = base::unixtime::now(); const auto notMuted = muteForSeconds ? !(*muteForSeconds) : (!_mute || *_mute <= now); @@ -170,13 +172,13 @@ bool NotifySettings::change( const auto flags = (muteForSeconds ? Flag::f_mute_until : Flag(0)) | (silentPosts ? Flag::f_silent : Flag(0)); const auto muteUntil = muteForSeconds - ? (unixtime() + *muteForSeconds) + ? (base::unixtime::now() + *muteForSeconds) : 0; return change(MTP_peerNotifySettings( MTP_flags(flags), MTPBool(), silentPosts ? MTP_bool(*silentPosts) : MTPBool(), - muteForSeconds ? MTP_int(unixtime() + *muteForSeconds) : MTPint(), + muteForSeconds ? MTP_int(base::unixtime::now() + *muteForSeconds) : MTPint(), MTPstring())); } diff --git a/Telegram/SourceFiles/data/data_peer_values.cpp b/Telegram/SourceFiles/data/data_peer_values.cpp index bd24cf948..9fb8cfc30 100644 --- a/Telegram/SourceFiles/data/data_peer_values.cpp +++ b/Telegram/SourceFiles/data/data_peer_values.cpp @@ -11,6 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_channel.h" #include "data/data_chat.h" #include "data/data_user.h" +#include "base/unixtime.h" namespace Data { namespace { @@ -37,7 +38,7 @@ int OnlinePhraseChangeInSeconds(TimeId online, TimeId now) { if (hours < 12) { return (hours + 1) * 3600 - (now - online); } - const auto nowFull = ParseDateTime(now); + const auto nowFull = base::unixtime::parse(now); const auto tomorrow = QDateTime(nowFull.date().addDays(1)); return std::max(static_cast(nowFull.secsTo(tomorrow)), 0); } @@ -305,8 +306,8 @@ QString OnlineText(TimeId online, TimeId now) { if (hours < 12) { return tr::lng_status_lastseen_hours(tr::now, lt_count, hours); } - const auto onlineFull = ParseDateTime(online); - const auto nowFull = ParseDateTime(now); + const auto onlineFull = base::unixtime::parse(online); + const auto nowFull = base::unixtime::parse(now); if (onlineFull.date() == nowFull.date()) { const auto onlineTime = onlineFull.time().toString(cTimeFormat()); return tr::lng_status_lastseen_today(tr::now, lt_time, onlineTime); @@ -331,8 +332,8 @@ QString OnlineTextFull(not_null user, TimeId now) { } else if (const auto common = OnlineTextCommon(user->onlineTill, now)) { return *common; } - const auto onlineFull = ParseDateTime(user->onlineTill); - const auto nowFull = ParseDateTime(now); + const auto onlineFull = base::unixtime::parse(user->onlineTill); + const auto nowFull = base::unixtime::parse(now); if (onlineFull.date() == nowFull.date()) { const auto onlineTime = onlineFull.time().toString(cTimeFormat()); return tr::lng_status_lastseen_today(tr::now, lt_time, onlineTime); @@ -368,7 +369,7 @@ bool OnlineTextActive(not_null user, TimeId now) { bool IsPeerAnOnlineUser(not_null peer) { if (const auto user = peer->asUser()) { - return OnlineTextActive(user, unixtime()); + return OnlineTextActive(user, base::unixtime::now()); } return false; } diff --git a/Telegram/SourceFiles/data/data_session.cpp b/Telegram/SourceFiles/data/data_session.cpp index ea2b4012e..a3ec11843 100644 --- a/Telegram/SourceFiles/data/data_session.cpp +++ b/Telegram/SourceFiles/data/data_session.cpp @@ -44,6 +44,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_web_page.h" #include "data/data_game.h" #include "data/data_poll.h" +#include "base/unixtime.h" #include "styles/style_boxes.h" // st::backgroundSize namespace Data { @@ -915,7 +916,7 @@ void Session::suggestStartExport() { return; } - const auto now = unixtime(); + const auto now = base::unixtime::now(); const auto left = (_exportAvailableAt <= now) ? 0 : (_exportAvailableAt - now); @@ -2243,7 +2244,7 @@ PhotoData *Session::photoFromWeb( rand_value(), uint64(0), QByteArray(), - unixtime(), + base::unixtime::now(), 0, false, thumbnailInline, @@ -2476,7 +2477,7 @@ DocumentData *Session::documentFromWeb( rand_value(), uint64(0), QByteArray(), - unixtime(), + base::unixtime::now(), data.vattributes().v, data.vmime_type().v, ImagePtr(), @@ -2497,7 +2498,7 @@ DocumentData *Session::documentFromWeb( rand_value(), uint64(0), QByteArray(), - unixtime(), + base::unixtime::now(), data.vattributes().v, data.vmime_type().v, ImagePtr(), @@ -2624,7 +2625,7 @@ not_null Session::processWebpage(const MTPDwebPagePending &data) { QString(), data.vdate().v ? data.vdate().v - : (unixtime() + kDefaultPendingTimeout)); + : (base::unixtime::now() + kDefaultPendingTimeout)); return result; } @@ -3455,7 +3456,7 @@ bool Session::notifyIsMuted( not_null peer, crl::time *changesIn) const { const auto resultFromUntil = [&](TimeId until) { - const auto now = unixtime(); + const auto now = base::unixtime::now(); const auto result = (until > now) ? (until - now) : 0; if (changesIn) { *changesIn = (result > 0) @@ -3532,7 +3533,7 @@ rpl::producer<> Session::defaultNotifyUpdates( void Session::serviceNotification( const TextWithEntities &message, const MTPMessageMedia &media) { - const auto date = unixtime(); + const auto date = base::unixtime::now(); if (!peerLoaded(PeerData::kServiceNotificationsId)) { processUser(MTP_user( MTP_flags( diff --git a/Telegram/SourceFiles/dialogs/dialogs_inner_widget.cpp b/Telegram/SourceFiles/dialogs/dialogs_inner_widget.cpp index ac4b27f3b..41a0e05b0 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_inner_widget.cpp +++ b/Telegram/SourceFiles/dialogs/dialogs_inner_widget.cpp @@ -25,6 +25,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_chat.h" #include "data/data_user.h" #include "data/data_peer_values.h" +#include "base/unixtime.h" #include "lang/lang_keys.h" #include "mainwindow.h" #include "mainwidget.h" @@ -2889,7 +2890,7 @@ void InnerWidget::userOnlineUpdated(const Notify::PeerUpdate &update) { const auto visible = (top < _visibleBottom) && (top + st::dialogsRowHeight > _visibleTop); row->setOnline( - Data::OnlineTextActive(user, unixtime()), + Data::OnlineTextActive(user, base::unixtime::now()), visible ? Fn(crl::guard(this, repaint)) : nullptr); } } diff --git a/Telegram/SourceFiles/dialogs/dialogs_layout.cpp b/Telegram/SourceFiles/dialogs/dialogs_layout.cpp index f184e2bac..4b54adced 100644 --- a/Telegram/SourceFiles/dialogs/dialogs_layout.cpp +++ b/Telegram/SourceFiles/dialogs/dialogs_layout.cpp @@ -22,6 +22,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "history/history_item_components.h" #include "history/history_item.h" #include "history/history.h" +#include "base/unixtime.h" #include "data/data_channel.h" #include "data/data_user.h" #include "data/data_folder.h" @@ -639,11 +640,13 @@ void RowPainter::paint( if (cloudDraft) { return (item->date() > cloudDraft->date) ? ItemDateTime(item) - : ParseDateTime(cloudDraft->date); + : base::unixtime::parse(cloudDraft->date); } return ItemDateTime(item); } - return cloudDraft ? ParseDateTime(cloudDraft->date) : QDateTime(); + return cloudDraft + ? base::unixtime::parse(cloudDraft->date) + : QDateTime(); }(); const auto displayMentionBadge = history ? history->hasUnreadMentions() diff --git a/Telegram/SourceFiles/export/view/export_view_panel_controller.cpp b/Telegram/SourceFiles/export/view/export_view_panel_controller.cpp index 3ba7b7856..0b7f96669 100644 --- a/Telegram/SourceFiles/export/view/export_view_panel_controller.cpp +++ b/Telegram/SourceFiles/export/view/export_view_panel_controller.cpp @@ -19,6 +19,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "platform/platform_info.h" #include "auth_session.h" #include "data/data_session.h" +#include "base/unixtime.h" #include "styles/style_export.h" #include "styles/style_boxes.h" @@ -208,7 +209,7 @@ void PanelController::showError(const ApiErrorState &error) { lt_date, langDateTimeFull(when))); - _settings->availableAt = unixtime() + seconds; + _settings->availableAt = base::unixtime::now() + seconds; _saveSettingsTimer.callOnce(kSaveSettingsTimeout); Auth().data().suggestStartExport(_settings->availableAt); diff --git a/Telegram/SourceFiles/export/view/export_view_settings.cpp b/Telegram/SourceFiles/export/view/export_view_settings.cpp index 5e01cd104..ce023ebe3 100644 --- a/Telegram/SourceFiles/export/view/export_view_settings.cpp +++ b/Telegram/SourceFiles/export/view/export_view_settings.cpp @@ -23,6 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "platform/platform_specific.h" #include "core/file_utilities.h" #include "boxes/calendar_box.h" +#include "base/unixtime.h" #include "auth_session.h" #include "styles/style_widgets.h" #include "styles/style_export.h" @@ -284,7 +285,8 @@ void SettingsWidget::addLimitsLabel( }) | rpl::distinct_until_changed( ) | rpl::map([](TimeId from) { return (from - ? rpl::single(langDayOfMonthFull(ParseDateTime(from).date())) + ? rpl::single(langDayOfMonthFull( + base::unixtime::parse(from).date())) : tr::lng_export_beginning() ) | Ui::Text::ToLink(qsl("internal:edit_from")); }) | rpl::flatten_latest(); @@ -294,7 +296,8 @@ void SettingsWidget::addLimitsLabel( }) | rpl::distinct_until_changed( ) | rpl::map([](TimeId till) { return (till - ? rpl::single(langDayOfMonthFull(ParseDateTime(till).date())) + ? rpl::single(langDayOfMonthFull( + base::unixtime::parse(till).date())) : tr::lng_export_end() ) | Ui::Text::ToLink(qsl("internal:edit_till")); }) | rpl::flatten_latest(); @@ -360,20 +363,20 @@ void SettingsWidget::editDateLimit( Expects(_showBoxCallback != nullptr); const auto highlighted = current - ? ParseDateTime(current).date() + ? base::unixtime::parse(current).date() : max - ? ParseDateTime(max).date() + ? base::unixtime::parse(max).date() : min - ? ParseDateTime(min).date() + ? base::unixtime::parse(min).date() : QDate::currentDate(); const auto month = highlighted; const auto shared = std::make_shared>(); const auto finalize = [=](not_null box) { box->setMaxDate(max - ? ParseDateTime(max).date() + ? base::unixtime::parse(max).date() : QDate::currentDate()); box->setMinDate(min - ? ParseDateTime(min).date() + ? base::unixtime::parse(min).date() : QDate(2013, 8, 1)); // Telegram was launched in August 2013 :) box->addLeftButton(std::move(resetLabel), crl::guard(this, [=] { done(0); @@ -383,7 +386,7 @@ void SettingsWidget::editDateLimit( })); }; const auto callback = crl::guard(this, [=](const QDate &date) { - done(ServerTimeFromParsed(QDateTime(date))); + done(base::unixtime::serialize(QDateTime(date))); if (const auto weak = shared->data()) { weak->closeBox(); } diff --git a/Telegram/SourceFiles/history/admin_log/history_admin_log_filter.cpp b/Telegram/SourceFiles/history/admin_log/history_admin_log_filter.cpp index 3aad8d5df..0957f3360 100644 --- a/Telegram/SourceFiles/history/admin_log/history_admin_log_filter.cpp +++ b/Telegram/SourceFiles/history/admin_log/history_admin_log_filter.cpp @@ -13,6 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_peer_values.h" #include "data/data_channel.h" #include "data/data_user.h" +#include "base/unixtime.h" #include "styles/style_boxes.h" namespace AdminLog { @@ -72,7 +73,7 @@ UserCheckbox::UserCheckbox(QWidget *parent, not_null user, bool check if (isDisabled()) return; setChecked(!this->checked()); }); - auto now = unixtime(); + auto now = base::unixtime::now(); _statusText = Data::OnlineText(_user, now); _statusOnline = Data::OnlineTextActive(_user, now); auto checkSize = _check->getSize(); diff --git a/Telegram/SourceFiles/history/admin_log/history_admin_log_item.cpp b/Telegram/SourceFiles/history/admin_log/history_admin_log_item.cpp index 8ecd796ad..d37537f31 100644 --- a/Telegram/SourceFiles/history/admin_log/history_admin_log_item.cpp +++ b/Telegram/SourceFiles/history/admin_log/history_admin_log_item.cpp @@ -19,6 +19,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lang/lang_keys.h" #include "ui/text/text_utilities.h" #include "boxes/sticker_set_box.h" +#include "base/unixtime.h" #include "core/application.h" #include "mainwindow.h" // App::wnd()->sessionController #include "auth_session.h" @@ -218,7 +219,7 @@ TextWithEntities GenerateBannedChangeText( : tr::lng_admin_log_restricted_until( tr::now, lt_date, - langDateTime(ParseDateTime(newUntil))); + langDateTime(base::unixtime::parse(newUntil))); auto result = tr::lng_admin_log_restricted( tr::now, lt_user, diff --git a/Telegram/SourceFiles/history/history.cpp b/Telegram/SourceFiles/history/history.cpp index a2e7d74e8..26b34ae42 100644 --- a/Telegram/SourceFiles/history/history.cpp +++ b/Telegram/SourceFiles/history/history.cpp @@ -39,6 +39,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/image/image.h" #include "ui/text_options.h" #include "core/crash_reports.h" +#include "base/unixtime.h" #include "styles/style_dialogs.h" #include @@ -256,7 +257,7 @@ Data::Draft *History::createCloudDraft(const Data::Draft *fromDraft) { existing->cursor = fromDraft->cursor; existing->previewCancelled = fromDraft->previewCancelled; } - existing->date = unixtime(); + existing->date = base::unixtime::now(); } cloudDraftTextCache.clear(); @@ -285,7 +286,7 @@ void History::clearSentDraftText(const QString &text) { if (_lastSentDraftText && *_lastSentDraftText == text) { _lastSentDraftText = std::nullopt; } - accumulate_max(_lastSentDraftTime, unixtime()); + accumulate_max(_lastSentDraftTime, base::unixtime::now()); } void History::setEditDraft(std::unique_ptr &&draft) { diff --git a/Telegram/SourceFiles/history/history_inner_widget.cpp b/Telegram/SourceFiles/history/history_inner_widget.cpp index 1a9862c71..7c94a1405 100644 --- a/Telegram/SourceFiles/history/history_inner_widget.cpp +++ b/Telegram/SourceFiles/history/history_inner_widget.cpp @@ -34,6 +34,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "chat_helpers/message_field.h" #include "chat_helpers/stickers.h" #include "history/history_widget.h" +#include "base/unixtime.h" #include "mainwindow.h" #include "mainwidget.h" #include "layout.h" @@ -1508,7 +1509,7 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) { _widget->replyToMessage(itemId); }); } - if (item->allowsEdit(unixtime())) { + if (item->allowsEdit(base::unixtime::now())) { _menu->addAction(tr::lng_context_edit_msg(tr::now), [=] { _widget->editMessage(itemId); }); @@ -3109,7 +3110,7 @@ QString HistoryInner::tooltipText() const { dateText += '\n' + tr::lng_edited_date( tr::now, lt_date, - ParseDateTime(editedDate).toString( + base::unixtime::parse(editedDate).toString( QLocale::system().dateTimeFormat( QLocale::LongFormat))); } @@ -3117,7 +3118,7 @@ QString HistoryInner::tooltipText() const { dateText += '\n' + tr::lng_forwarded_date( tr::now, lt_date, - ParseDateTime(forwarded->originalDate).toString( + base::unixtime::parse(forwarded->originalDate).toString( QLocale::system().dateTimeFormat( QLocale::LongFormat))); if (const auto media = view->media()) { diff --git a/Telegram/SourceFiles/history/history_item.cpp b/Telegram/SourceFiles/history/history_item.cpp index a93091d95..3f9a1af37 100644 --- a/Telegram/SourceFiles/history/history_item.cpp +++ b/Telegram/SourceFiles/history/history_item.cpp @@ -31,6 +31,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mainwindow.h" #include "window/window_session_controller.h" #include "core/crash_reports.h" +#include "base/unixtime.h" #include "data/data_session.h" #include "data/data_messages.h" #include "data/data_media_types.h" @@ -271,7 +272,7 @@ void HistoryItem::finishEditionToEmpty() { bool HistoryItem::hasUnreadMediaFlag() const { if (_history->peer->isChannel()) { - const auto passed = unixtime() - date(); + const auto passed = base::unixtime::now() - date(); if (passed >= Global::ChannelsReadMediaPeriod()) { return false; } @@ -781,7 +782,7 @@ void HistoryItem::drawInDialog( HistoryItem::~HistoryItem() = default; QDateTime ItemDateTime(not_null item) { - return ParseDateTime(item->date()); + return base::unixtime::parse(item->date()); } ClickHandlerPtr goToMessageClickHandler( diff --git a/Telegram/SourceFiles/history/history_widget.cpp b/Telegram/SourceFiles/history/history_widget.cpp index beb0fd115..bdb7165e7 100644 --- a/Telegram/SourceFiles/history/history_widget.cpp +++ b/Telegram/SourceFiles/history/history_widget.cpp @@ -25,6 +25,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/image/image.h" #include "ui/special_buttons.h" #include "inline_bots/inline_bot_result.h" +#include "base/unixtime.h" #include "data/data_drafts.h" #include "data/data_session.h" #include "data/data_web_page.h" @@ -4305,7 +4306,7 @@ void HistoryWidget::sendFileConfirmed( MTPMessageFwdHeader(), MTPint(), MTP_int(file->to.replyTo), - MTP_int(unixtime()), + MTP_int(base::unixtime::now()), MTP_string(caption.text), photo, MTPReplyMarkup(), @@ -4336,7 +4337,7 @@ void HistoryWidget::sendFileConfirmed( MTPMessageFwdHeader(), MTPint(), MTP_int(file->to.replyTo), - MTP_int(unixtime()), + MTP_int(base::unixtime::now()), MTP_string(caption.text), document, MTPReplyMarkup(), @@ -4370,7 +4371,7 @@ void HistoryWidget::sendFileConfirmed( MTPMessageFwdHeader(), MTPint(), MTP_int(file->to.replyTo), - MTP_int(unixtime()), + MTP_int(base::unixtime::now()), MTP_string(caption.text), document, MTPReplyMarkup(), @@ -5154,7 +5155,7 @@ void HistoryWidget::keyPressEvent(QKeyEvent *e) { ? _history->lastSentMessage() : nullptr; if (item - && item->allowsEdit(unixtime()) + && item->allowsEdit(base::unixtime::now()) && _field->empty() && !_editMsgId && !_replyToId) { @@ -5503,7 +5504,7 @@ bool HistoryWidget::sendExistingPhoto( flags, 0, options.replyTo, - unixtime(), + base::unixtime::now(), messageFromId, messagePostAuthor, photo, @@ -5928,7 +5929,7 @@ void HistoryWidget::gotPreview(QString links, const MTPMessageMedia &result, mtp const auto &data = result.c_messageMediaWebPage().vwebpage(); const auto page = session().data().processWebpage(data); _previewCache.insert(links, page->id); - if (page->pendingTill > 0 && page->pendingTill <= unixtime()) { + if (page->pendingTill > 0 && page->pendingTill <= base::unixtime::now()) { page->pendingTill = -1; } if (links == _previewLinks && !_previewCancelled) { @@ -5967,7 +5968,7 @@ void HistoryWidget::updatePreview() { TextUtilities::Clean(linkText), Ui::DialogTextOptions()); - const auto timeout = (_previewData->pendingTill - unixtime()); + const auto timeout = (_previewData->pendingTill - base::unixtime::now()); _previewTimer.callOnce(std::max(timeout, 0) * crl::time(1000)); } else { QString title, desc; diff --git a/Telegram/SourceFiles/history/view/history_view_top_bar_widget.cpp b/Telegram/SourceFiles/history/view/history_view_top_bar_widget.cpp index e4bf90dde..9d168ff1b 100644 --- a/Telegram/SourceFiles/history/view/history_view_top_bar_widget.cpp +++ b/Telegram/SourceFiles/history/view/history_view_top_bar_widget.cpp @@ -34,6 +34,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_channel.h" #include "data/data_chat.h" #include "data/data_user.h" +#include "base/unixtime.h" #include "support/support_helper.h" #include "observer_peer.h" #include "apiwrap.h" @@ -775,7 +776,7 @@ void TopBarWidget::updateOnlineDisplay() { if (!_activeChat.peer()) return; QString text; - const auto now = unixtime(); + const auto now = base::unixtime::now(); bool titlePeerTextOnline = false; if (const auto user = _activeChat.peer()->asUser()) { if (Auth().supportMode() @@ -861,7 +862,7 @@ void TopBarWidget::updateOnlineDisplay() { void TopBarWidget::updateOnlineDisplayTimer() { if (!_activeChat.peer()) return; - const auto now = unixtime(); + const auto now = base::unixtime::now(); auto minTimeout = crl::time(86400); const auto handleUser = [&](not_null user) { auto hisTimeout = Data::OnlineChangeTimeout(user, now); diff --git a/Telegram/SourceFiles/info/profile/info_profile_cover.cpp b/Telegram/SourceFiles/info/profile/info_profile_cover.cpp index cdbda619b..bb2cdaecc 100644 --- a/Telegram/SourceFiles/info/profile/info_profile_cover.cpp +++ b/Telegram/SourceFiles/info/profile/info_profile_cover.cpp @@ -23,6 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/text/text_utilities.h" // Ui::Text::ToUpper #include "ui/special_buttons.h" #include "ui/unread_badge.h" +#include "base/unixtime.h" #include "window/window_session_controller.h" #include "observer_peer.h" #include "core/application.h" @@ -394,7 +395,7 @@ void Cover::refreshStatusText() { return false; }(); auto statusText = [&] { - auto currentTime = unixtime(); + auto currentTime = base::unixtime::now(); if (auto user = _peer->asUser()) { const auto result = Data::OnlineTextFull(user, currentTime); const auto showOnline = Data::OnlineTextActive(user, currentTime); diff --git a/Telegram/SourceFiles/mainwidget.cpp b/Telegram/SourceFiles/mainwidget.cpp index 6528625bb..d68fada72 100644 --- a/Telegram/SourceFiles/mainwidget.cpp +++ b/Telegram/SourceFiles/mainwidget.cpp @@ -83,6 +83,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "core/update_checker.h" #include "core/shortcuts.h" #include "core/application.h" +#include "base/unixtime.h" #include "calls/calls_instance.h" #include "calls/calls_top_bar.h" #include "export/export_settings.h" @@ -3417,7 +3418,7 @@ void MainWidget::incrementSticker(DocumentData *sticker) { } if (index) { if (it->dates.size() == it->stickers.size()) { - it->dates.insert(it->dates.begin(), unixtime()); + it->dates.insert(it->dates.begin(), base::unixtime::now()); } it->stickers.push_front(sticker); if (const auto emojiList = Stickers::GetEmojiListFromSet(sticker)) { @@ -3579,7 +3580,7 @@ void MainWidget::updateOnline(bool gotOtherOffline) { } const auto self = session().user(); - self->onlineTill = unixtime() + (isOnline ? (Global::OnlineUpdatePeriod() / 1000) : -1); + self->onlineTill = base::unixtime::now() + (isOnline ? (Global::OnlineUpdatePeriod() / 1000) : -1); Notify::peerUpdatedDelayed( self, Notify::PeerUpdate::Flag::UserOnlineChanged); @@ -4008,7 +4009,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) { history->outboxRead(d.vmax_id().v); if (!requestingDifference()) { if (const auto user = history->peer->asUser()) { - user->madeAction(unixtime()); + user->madeAction(base::unixtime::now()); } } if (_history->peer() && _history->peer()->id == peer) { @@ -4117,7 +4118,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) { const auto history = session().data().historyLoaded(userId); const auto user = session().data().userLoaded(d.vuser_id().v); if (history && user) { - const auto when = requestingDifference() ? 0 : unixtime(); + const auto when = requestingDifference() ? 0 : base::unixtime::now(); session().data().registerSendAction(history, user, d.vaction(), when); } } break; @@ -4136,7 +4137,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) { ? nullptr : session().data().userLoaded(d.vuser_id().v); if (history && user) { - const auto when = requestingDifference() ? 0 : unixtime(); + const auto when = requestingDifference() ? 0 : base::unixtime::now(); session().data().registerSendAction(history, user, d.vaction(), when); } } break; diff --git a/Telegram/SourceFiles/media/view/media_view_overlay_widget.cpp b/Telegram/SourceFiles/media/view/media_view_overlay_widget.cpp index 040825117..60365dea9 100644 --- a/Telegram/SourceFiles/media/view/media_view_overlay_widget.cpp +++ b/Telegram/SourceFiles/media/view/media_view_overlay_widget.cpp @@ -38,6 +38,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "window/window_peer_menu.h" #include "window/window_controller.h" #include "main/main_account.h" // Account::sessionValue. +#include "base/unixtime.h" #include "observer_peer.h" #include "auth_session.h" #include "layout.h" @@ -554,9 +555,9 @@ void OverlayWidget::updateControls() { if (const auto item = Auth().data().message(_msgid)) { return ItemDateTime(item); } else if (_photo) { - return ParseDateTime(_photo->date); + return base::unixtime::parse(_photo->date); } else if (_doc) { - return ParseDateTime(_doc->date); + return base::unixtime::parse(_doc->date); } return dNow; }(); diff --git a/Telegram/SourceFiles/mtproto/config_loader.cpp b/Telegram/SourceFiles/mtproto/config_loader.cpp index 81501301b..890c15b00 100644 --- a/Telegram/SourceFiles/mtproto/config_loader.cpp +++ b/Telegram/SourceFiles/mtproto/config_loader.cpp @@ -24,13 +24,11 @@ ConfigLoader::ConfigLoader( not_null instance, const QString &phone, RPCDoneHandlerPtr onDone, - RPCFailHandlerPtr onFail, - Fn updateHttpUnixtime) + RPCFailHandlerPtr onFail) : _instance(instance) , _phone(phone) , _doneHandler(onDone) -, _failHandler(onFail) -, _updateHttpUnixtime(updateHttpUnixtime) { +, _failHandler(onFail) { _enumDCTimer.setCallback([this] { enumerate(); }); _specialEnumTimer.setCallback([this] { sendSpecialRequest(); }); } @@ -131,7 +129,7 @@ void ConfigLoader::createSpecialLoader() { int port, bytes::const_span secret) { addSpecialEndpoint(dcId, ip, port, secret); - }, _updateHttpUnixtime, _phone); + }, _phone); } void ConfigLoader::addSpecialEndpoint( diff --git a/Telegram/SourceFiles/mtproto/config_loader.h b/Telegram/SourceFiles/mtproto/config_loader.h index f9166bed1..923dc2e25 100644 --- a/Telegram/SourceFiles/mtproto/config_loader.h +++ b/Telegram/SourceFiles/mtproto/config_loader.h @@ -25,8 +25,7 @@ public: not_null instance, const QString &phone, RPCDoneHandlerPtr onDone, - RPCFailHandlerPtr onFail, - Fn updateHttpUnixtime); + RPCFailHandlerPtr onFail); ~ConfigLoader(); void load(); @@ -70,7 +69,6 @@ private: RPCDoneHandlerPtr _doneHandler; RPCFailHandlerPtr _failHandler; - Fn _updateHttpUnixtime; }; diff --git a/Telegram/SourceFiles/mtproto/connection.cpp b/Telegram/SourceFiles/mtproto/connection.cpp index 1f6535c0f..160b41c6a 100644 --- a/Telegram/SourceFiles/mtproto/connection.cpp +++ b/Telegram/SourceFiles/mtproto/connection.cpp @@ -18,6 +18,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lang/lang_keys.h" #include "base/openssl_help.h" #include "base/qthelp_url.h" +#include "base/unixtime.h" extern "C" { #include @@ -380,7 +381,9 @@ void ConnectionPrivate::appendTestConnection( onDisconnected(weak); }); connect(weak, &AbstractConnection::syncTimeRequest, [=] { - _instance->syncHttpUnixtime(); + InvokeQueued(_instance, [instance = _instance] { + instance->syncHttpUnixtime(); + }); }); InvokeQueued(_testConnections.back().data, [=] { @@ -526,7 +529,7 @@ void ConnectionPrivate::resetSession() { // recreate all msg_id and msg_seqno auto &toSend = sessionData->toSendMap(); auto &wereAcked = sessionData->wereAckedMap(); - auto newId = msgid(); + auto newId = base::unixtime::mtproto_msg_id(); auto setSeqNumbers = RequestMap(); auto replaces = QMap(); for (auto i = haveSent.cbegin(), e = haveSent.cend(); i != e; ++i) { @@ -539,7 +542,7 @@ void ConnectionPrivate::resetSession() { // recreate all msg_id and msg_seqno if (toResend.constFind(newId) == toResend.cend() && wereAcked.constFind(newId) == wereAcked.cend() && haveSent.constFind(newId) == haveSent.cend()) { break; } - mtpMsgId m = msgid(); + const auto m = base::unixtime::mtproto_msg_id(); if (m <= newId) break; // wtf newId = m; @@ -566,7 +569,7 @@ void ConnectionPrivate::resetSession() { // recreate all msg_id and msg_seqno if (toResend.constFind(newId) == toResend.cend() && wereAcked.constFind(newId) == wereAcked.cend() && haveSent.constFind(newId) == haveSent.cend()) { break; } - mtpMsgId m = msgid(); + const auto m = base::unixtime::mtproto_msg_id(); if (m <= newId) break; // wtf newId = m; @@ -667,7 +670,7 @@ mtpMsgId ConnectionPrivate::replaceMsgId(SecureRequest &request, mtpMsgId newId) if (toResend.constFind(newId) == toResend.cend() && wereAcked.constFind(newId) == wereAcked.cend() && haveSent.constFind(newId) == haveSent.cend()) { break; } - const auto m = msgid(); + const auto m = base::unixtime::mtproto_msg_id(); if (m <= newId) break; // wtf newId = m; @@ -714,9 +717,13 @@ mtpMsgId ConnectionPrivate::replaceMsgId(SecureRequest &request, mtpMsgId newId) } mtpMsgId ConnectionPrivate::placeToContainer(SecureRequest &toSendRequest, mtpMsgId &bigMsgId, mtpMsgId *&haveSentArr, SecureRequest &req) { - mtpMsgId msgId = prepareToSend(req, bigMsgId); - if (msgId > bigMsgId) msgId = replaceMsgId(req, bigMsgId); - if (msgId >= bigMsgId) bigMsgId = msgid(); + auto msgId = prepareToSend(req, bigMsgId); + if (msgId > bigMsgId) { + msgId = replaceMsgId(req, bigMsgId); + } + if (msgId >= bigMsgId) { + bigMsgId = base::unixtime::mtproto_msg_id(); + } *(haveSentArr++) = msgId; uint32 from = toSendRequest->size(), len = req.messageSize(); @@ -890,7 +897,9 @@ void ConnectionPrivate::tryToSend() { locker1.unlock(); } - mtpMsgId msgId = prepareToSend(toSendRequest, msgid()); + const auto msgId = prepareToSend( + toSendRequest, + base::unixtime::mtproto_msg_id()); if (pingRequest) { _pingMsgId = msgId; needAnyResponse = true; @@ -965,7 +974,8 @@ void ConnectionPrivate::tryToSend() { toSendRequest->push_back(mtpc_msg_container); toSendRequest->push_back(toSendCount); - mtpMsgId bigMsgId = msgid(); // check for a valid container + // check for a valid container + auto bigMsgId = base::unixtime::mtproto_msg_id(); // the fact of this lock is used in replaceMsgId() QWriteLocker locker2(sessionData->haveSentMutex()); @@ -990,8 +1000,12 @@ void ConnectionPrivate::tryToSend() { for (auto i = toSend.begin(), e = toSend.end(); i != e; ++i) { auto &req = i.value(); auto msgId = prepareToSend(req, bigMsgId); - if (msgId > bigMsgId) msgId = replaceMsgId(req, bigMsgId); - if (msgId >= bigMsgId) bigMsgId = msgid(); + if (msgId > bigMsgId) { + msgId = replaceMsgId(req, bigMsgId); + } + if (msgId >= bigMsgId) { + bigMsgId = base::unixtime::mtproto_msg_id(); + } *(haveSentArr++) = msgId; bool added = false; if (req->requestId) { @@ -1523,8 +1537,9 @@ void ConnectionPrivate::handleReceived() { return restartOnError(); } - int32 serverTime((int32)(msgId >> 32)), clientTime(unixtime()); - bool isReply = ((msgId & 0x03) == 1); + const auto serverTime = int32(msgId >> 32); + const auto clientTime = base::unixtime::now(); + const auto isReply = ((msgId & 0x03) == 1); if (!isReply && ((msgId & 0x03) != 3)) { LOG(("MTP Error: bad msg_id %1 in message received").arg(msgId)); @@ -1768,7 +1783,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr if (needResend) { // bad msg_id or bad container if (serverSalt) sessionData->setSalt(serverSalt); - unixtimeSet(serverTime, true); + base::unixtime::update(serverTime, true); DEBUG_LOG(("Message Info: unixtime updated, now %1, resending in container...").arg(serverTime)); @@ -1776,7 +1791,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr } else { // must create new session, because msg_id and msg_seqno are inconsistent if (badTime) { if (serverSalt) sessionData->setSalt(serverSalt); - unixtimeSet(serverTime, true); + base::unixtime::update(serverTime, true); badTime = false; } LOG(("Message Info: bad message notification received, msgId %1, error_code %2").arg(data.vbad_msg_id().v).arg(errorCode)); @@ -1821,7 +1836,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr uint64 serverSalt = data.vnew_server_salt().v; sessionData->setSalt(serverSalt); - unixtimeSet(serverTime); + base::unixtime::update(serverTime); if (setState(ConnectedState, ConnectingState)) { // maybe only connected if (restarted) { @@ -1908,7 +1923,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr } if (badTime) { if (serverSalt) sessionData->setSalt(serverSalt); // requestsFixTimeSalt with no lookup - unixtimeSet(serverTime, true); + base::unixtime::update(serverTime, true); DEBUG_LOG(("Message Info: unixtime updated from mtpc_msgs_state_info, now %1").arg(serverTime)); @@ -2243,7 +2258,7 @@ bool ConnectionPrivate::requestsFixTimeSalt(const QVector &ids, int32 s for (uint32 i = 0; i < idsCount; ++i) { if (wasSent(ids[i].v)) {// found such msg_id in recent acked requests or in recent sent requests if (serverSalt) sessionData->setSalt(serverSalt); - unixtimeSet(serverTime, true); + base::unixtime::update(serverTime, true); return true; } } @@ -2733,7 +2748,7 @@ 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())); return restart(); } - unixtimeSet(dh_inner_data.vserver_time().v); + base::unixtime::update(dh_inner_data.vserver_time().v); // 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)) { @@ -3053,7 +3068,9 @@ void ConnectionPrivate::onReadyData() { template void ConnectionPrivate::sendNotSecureRequest(const Request &request) { - auto packet = _connection->prepareNotSecurePacket(request); + auto packet = _connection->prepareNotSecurePacket( + request, + base::unixtime::mtproto_msg_id()); DEBUG_LOG(("AuthKey Info: sending request, size: %1, time: %3" ).arg(packet.size() - 8 diff --git a/Telegram/SourceFiles/mtproto/connection_abstract.cpp b/Telegram/SourceFiles/mtproto/connection_abstract.cpp index 8b20a126b..507247830 100644 --- a/Telegram/SourceFiles/mtproto/connection_abstract.cpp +++ b/Telegram/SourceFiles/mtproto/connection_abstract.cpp @@ -11,6 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mtproto/connection_http.h" #include "mtproto/connection_resolving.h" #include "mtproto/session.h" +#include "base/unixtime.h" namespace MTP { namespace internal { @@ -111,8 +112,8 @@ gsl::span AbstractConnection::parseNotSecureResponse( if (answer[0] != 0 || answer[1] != 0 || (((uint32)answer[2]) & 0x03) != 1 - //|| (unixtime() - answer[3] > 300) // We didn't sync time yet. - //|| (answer[3] - unixtime() > 60) + //|| (base::unixtime::now() - answer[3] > 300) // We didn't sync time yet. + //|| (answer[3] - base::unixtime::now() > 60) || false) { LOG(("Not Secure Error: bad request answer start (%1 %2 %3)" ).arg(answer[0] @@ -135,7 +136,9 @@ gsl::span AbstractConnection::parseNotSecureResponse( } mtpBuffer AbstractConnection::preparePQFake(const MTPint128 &nonce) const { - return prepareNotSecurePacket(MTPReq_pq(nonce)); + return prepareNotSecurePacket( + MTPReq_pq(nonce), + base::unixtime::mtproto_msg_id()); } MTPResPQ AbstractConnection::readPQFakeReply( diff --git a/Telegram/SourceFiles/mtproto/connection_abstract.h b/Telegram/SourceFiles/mtproto/connection_abstract.h index 28f773c58..3f92cb4d1 100644 --- a/Telegram/SourceFiles/mtproto/connection_abstract.h +++ b/Telegram/SourceFiles/mtproto/connection_abstract.h @@ -103,7 +103,9 @@ public: } template - mtpBuffer prepareNotSecurePacket(const Request &request) const; + mtpBuffer prepareNotSecurePacket( + const Request &request, + mtpMsgId newId) const; mtpBuffer prepareSecurePacket( uint64 keyId, MTPint128 msgKey, @@ -140,7 +142,9 @@ protected: }; template -mtpBuffer AbstractConnection::prepareNotSecurePacket(const Request &request) const { +mtpBuffer AbstractConnection::prepareNotSecurePacket( + const Request &request, + mtpMsgId newId) const { const auto intsSize = request.innerLength() >> 2; const auto intsPadding = requiresExtendedPadding() ? uint32(rand_value() & 0x3F) @@ -161,7 +165,7 @@ mtpBuffer AbstractConnection::prepareNotSecurePacket(const Request &request) con result.resize(kPrefixInts); const auto messageId = &result[kTcpPrefixInts + kAuthKeyIdInts]; - *reinterpret_cast(messageId) = msgid(); + *reinterpret_cast(messageId) = newId; request.write(result); diff --git a/Telegram/SourceFiles/mtproto/connection_tcp.cpp b/Telegram/SourceFiles/mtproto/connection_tcp.cpp index 749de0017..c0012f18e 100644 --- a/Telegram/SourceFiles/mtproto/connection_tcp.cpp +++ b/Telegram/SourceFiles/mtproto/connection_tcp.cpp @@ -558,8 +558,7 @@ void TcpConnection::connectToServer( _socket = AbstractSocket::Create( thread(), secret, - ToNetworkProxy(_proxy), - [=] { return _instance->httpUnixtime(); }); + ToNetworkProxy(_proxy)); _protocolDcId = protocolDcId; _socket->connected( diff --git a/Telegram/SourceFiles/mtproto/mtp_abstract_socket.cpp b/Telegram/SourceFiles/mtproto/mtp_abstract_socket.cpp index 6363ca2b4..1de6e6654 100644 --- a/Telegram/SourceFiles/mtproto/mtp_abstract_socket.cpp +++ b/Telegram/SourceFiles/mtproto/mtp_abstract_socket.cpp @@ -16,10 +16,9 @@ namespace internal { std::unique_ptr AbstractSocket::Create( not_null thread, const bytes::vector &secret, - const QNetworkProxy &proxy, - Fn unixtime) { + const QNetworkProxy &proxy) { if (secret.size() >= 21 && secret[0] == bytes::type(0xEE)) { - return std::make_unique(thread, secret, proxy, unixtime); + return std::make_unique(thread, secret, proxy); } else { return std::make_unique(thread, proxy); } diff --git a/Telegram/SourceFiles/mtproto/mtp_abstract_socket.h b/Telegram/SourceFiles/mtproto/mtp_abstract_socket.h index 522114fe7..4ac12bb75 100644 --- a/Telegram/SourceFiles/mtproto/mtp_abstract_socket.h +++ b/Telegram/SourceFiles/mtproto/mtp_abstract_socket.h @@ -18,8 +18,7 @@ public: static std::unique_ptr Create( not_null thread, const bytes::vector &secret, - const QNetworkProxy &proxy, - Fn unixtime); + const QNetworkProxy &proxy); explicit AbstractSocket(not_null thread) { moveToThread(thread); diff --git a/Telegram/SourceFiles/mtproto/mtp_instance.cpp b/Telegram/SourceFiles/mtproto/mtp_instance.cpp index 01d61d870..e5c89ea55 100644 --- a/Telegram/SourceFiles/mtproto/mtp_instance.cpp +++ b/Telegram/SourceFiles/mtproto/mtp_instance.cpp @@ -20,6 +20,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "auth_session.h" #include "apiwrap.h" #include "core/application.h" +#include "base/unixtime.h" #include "lang/lang_instance.h" #include "lang/lang_cloud_manager.h" #include "base/timer.h" @@ -60,10 +61,7 @@ public: void requestCDNConfig(); void setUserPhone(const QString &phone); void badConfigurationError(); - - // Thread safe. void syncHttpUnixtime(); - [[nodiscard]] int32 httpUnixtime() const; void restart(); void restart(ShiftedDcId shiftedDcId); @@ -168,7 +166,6 @@ private: void clearCallbacks(const std::vector &ids); void checkDelayedRequests(); - [[nodiscard]] Fn updateHttpUnixtime(); not_null _instance; not_null _dcOptions; @@ -194,8 +191,6 @@ private: mtpRequestId _cdnConfigLoadRequestId = 0; crl::time _lastConfigLoadedTime = 0; crl::time _configExpiresAt = 0; - std::atomic _httpUnixtimeValid = false; - std::atomic _httpUnixtimeShift = 0; std::map _keysForWrite; mutable QReadWriteLock _keysForWriteLock; @@ -250,8 +245,6 @@ void Instance::Private::start(Config &&config) { if (isKeysDestroyer()) { _instance->connect(_instance, SIGNAL(keyDestroyed(qint32)), _instance, SLOT(onKeyDestroyed(qint32)), Qt::QueuedConnection); - } else if (isNormal()) { - unixtimeInit(); } for (auto &key : config.keys) { @@ -413,8 +406,7 @@ void Instance::Private::requestConfig() { _instance, _userPhone, rpcDone([=](const MTPConfig &result) { configLoadDone(result); }), - rpcFail([=](const RPCError &error) { return configLoadFail(error); }), - updateHttpUnixtime()); + rpcFail([=](const RPCError &error) { return configLoadFail(error); })); _configLoader->load(); } @@ -433,33 +425,15 @@ void Instance::Private::badConfigurationError() { } } -int32 Instance::Private::httpUnixtime() const { - return unixtime() + _httpUnixtimeShift; -} - void Instance::Private::syncHttpUnixtime() { - if (_httpUnixtimeValid) { + if (base::unixtime::http_valid() || _httpUnixtimeLoader) { return; } - InvokeQueued(_instance, [=] { - if (_httpUnixtimeValid || _httpUnixtimeLoader) { - return; - } - _httpUnixtimeLoader = std::make_unique( - updateHttpUnixtime()); - }); -} - -Fn Instance::Private::updateHttpUnixtime() { - return [=](TimeId httpUnixtime) { - _httpUnixtimeValid = true; - _httpUnixtimeShift = httpUnixtime - unixtime(); + _httpUnixtimeLoader = std::make_unique([=] { InvokeQueued(_instance, [=] { - if (_httpUnixtimeValid) { - _httpUnixtimeLoader = nullptr; - } + _httpUnixtimeLoader = nullptr; }); - }; + }); } void Instance::Private::requestConfigIfOld() { @@ -842,7 +816,7 @@ void Instance::Private::configLoadDone(const MTPConfig &result) { Local::writeSettings(); _configExpiresAt = crl::now() - + (data.vexpires().v - unixtime()) * crl::time(1000); + + (data.vexpires().v - base::unixtime::now()) * crl::time(1000); requestConfigIfExpired(); emit _instance->configLoaded(); @@ -1615,10 +1589,6 @@ void Instance::badConfigurationError() { _private->badConfigurationError(); } -int32 Instance::httpUnixtime() const { - return _private->httpUnixtime(); -} - void Instance::syncHttpUnixtime() { _private->syncHttpUnixtime(); } diff --git a/Telegram/SourceFiles/mtproto/mtp_instance.h b/Telegram/SourceFiles/mtproto/mtp_instance.h index 8f1224dcf..c12d7432c 100644 --- a/Telegram/SourceFiles/mtproto/mtp_instance.h +++ b/Telegram/SourceFiles/mtproto/mtp_instance.h @@ -180,8 +180,6 @@ public: void setUserPhone(const QString &phone); void badConfigurationError(); - // Thread safe. - [[nodiscard]] int32 httpUnixtime() const; void syncHttpUnixtime(); ~Instance(); diff --git a/Telegram/SourceFiles/mtproto/mtp_tls_socket.cpp b/Telegram/SourceFiles/mtproto/mtp_tls_socket.cpp index ef0e1b918..4472cf6f0 100644 --- a/Telegram/SourceFiles/mtproto/mtp_tls_socket.cpp +++ b/Telegram/SourceFiles/mtproto/mtp_tls_socket.cpp @@ -11,6 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "base/openssl_help.h" #include "base/bytes.h" #include "base/invoke_queued.h" +#include "base/unixtime.h" #include @@ -136,8 +137,7 @@ public: ClientHelloGenerator( const MTPTlsClientHello &rules, bytes::const_span domain, - bytes::const_span key, - Fn unixtime); + bytes::const_span key); [[nodiscard]] ClientHello result(); private: @@ -156,7 +156,6 @@ private: bytes::const_span _domain; bytes::const_span _key; - Fn _unixtime; bytes::vector _greases; std::vector _scopeStack; QByteArray _result; @@ -169,11 +168,9 @@ private: ClientHelloGenerator::ClientHelloGenerator( const MTPTlsClientHello &rules, bytes::const_span domain, - bytes::const_span key, - Fn unixtime) + bytes::const_span key) : _domain(domain) , _key(key) -, _unixtime(unixtime) , _greases(PrepareGreases()) { _result.reserve(kClientHelloLength); writeBlocks(rules.match([&](const MTPDtlsClientHello &data) { @@ -304,7 +301,7 @@ void ClientHelloGenerator::writeTimestamp() { sizeof(int32)); auto already = int32(); bytes::copy(bytes::object_as_span(&already), storage); - already ^= qToLittleEndian(_unixtime()); + already ^= qToLittleEndian(int32(base::unixtime::http_now())); bytes::copy(storage, bytes::object_as_span(&already)); _digest = QByteArray(kHelloDigestLength, Qt::Uninitialized); @@ -318,9 +315,8 @@ void ClientHelloGenerator::writeTimestamp() { [[nodiscard]] ClientHello PrepareClientHello( const MTPTlsClientHello &rules, bytes::const_span domain, - bytes::const_span key, - Fn unixtime) { - return ClientHelloGenerator(rules, domain, key, unixtime).result(); + bytes::const_span key) { + return ClientHelloGenerator(rules, domain, key).result(); } [[nodiscard]] bool CheckPart(bytes::const_span data, QLatin1String check) { @@ -343,13 +339,10 @@ void ClientHelloGenerator::writeTimestamp() { TlsSocket::TlsSocket( not_null thread, const bytes::vector &secret, - const QNetworkProxy &proxy, - Fn unixtime) + const QNetworkProxy &proxy) : AbstractSocket(thread) -, _secret(secret) -, _unixtime(unixtime) { +, _secret(secret) { Expects(_secret.size() >= 21 && _secret[0] == bytes::type(0xEE)); - Expects(_unixtime != nullptr); _socket.moveToThread(thread); _socket.setProxy(proxy); @@ -397,8 +390,7 @@ void TlsSocket::plainConnected() { const auto hello = PrepareClientHello( kClientHelloRules, domainFromSecret(), - keyFromSecret(), - _unixtime); + keyFromSecret()); if (hello.data.isEmpty()) { LOG(("TLS Error: Could not generate Client Hello!")); _state = State::Error; diff --git a/Telegram/SourceFiles/mtproto/mtp_tls_socket.h b/Telegram/SourceFiles/mtproto/mtp_tls_socket.h index 10d4e50b8..e130e633e 100644 --- a/Telegram/SourceFiles/mtproto/mtp_tls_socket.h +++ b/Telegram/SourceFiles/mtproto/mtp_tls_socket.h @@ -17,8 +17,7 @@ public: TlsSocket( not_null thread, const bytes::vector &secret, - const QNetworkProxy &proxy, - Fn unixtime); + const QNetworkProxy &proxy); void connectToHost(const QString &address, int port) override; void timedOut() override; @@ -56,7 +55,6 @@ private: const bytes::vector _secret; QTcpSocket _socket; - Fn _unixtime; State _state = State::NotConnected; QByteArray _incoming; int _incomingGoodDataOffset = 0; diff --git a/Telegram/SourceFiles/mtproto/session.cpp b/Telegram/SourceFiles/mtproto/session.cpp index b0fcc751b..4b71becef 100644 --- a/Telegram/SourceFiles/mtproto/session.cpp +++ b/Telegram/SourceFiles/mtproto/session.cpp @@ -10,6 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mtproto/connection.h" #include "mtproto/dcenter.h" #include "mtproto/auth_key.h" +#include "base/unixtime.h" #include "core/crash_reports.h" namespace MTP { @@ -329,7 +330,8 @@ void Session::checkRequestsByTimer() { stateRequestIds.push_back(i.key()); } } - } else if (unixtime() > (int32)(i.key() >> 32) + kContainerLives) { + } else if (base::unixtime::now() + > int32(i.key() >> 32) + kContainerLives) { removingIds.reserve(haveSentCount); removingIds.push_back(i.key()); } diff --git a/Telegram/SourceFiles/mtproto/special_config_request.cpp b/Telegram/SourceFiles/mtproto/special_config_request.cpp index 9994dcc76..45820de68 100644 --- a/Telegram/SourceFiles/mtproto/special_config_request.cpp +++ b/Telegram/SourceFiles/mtproto/special_config_request.cpp @@ -10,6 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "mtproto/rsa_public_key.h" #include "mtproto/dc_options.h" #include "mtproto/auth_key.h" +#include "base/unixtime.h" #include "base/openssl_help.h" extern "C" { @@ -258,11 +259,13 @@ SpecialConfigRequest::SpecialConfigRequest( const std::string &ip, int port, bytes::const_span secret)> callback, - Fn timeCallback, + Fn timeDoneCallback, const QString &phone) : _callback(std::move(callback)) -, _timeCallback(std::move(timeCallback)) +, _timeDoneCallback(std::move(timeDoneCallback)) , _phone(phone) { + Expects((_callback == nullptr) != (_timeDoneCallback == nullptr)); + _manager.setProxy(QNetworkProxy::NoProxy); _attempts = { //{ Type::App, qsl("software-download.microsoft.com") }, @@ -275,8 +278,18 @@ SpecialConfigRequest::SpecialConfigRequest( sendNextRequest(); } -SpecialConfigRequest::SpecialConfigRequest(Fn timeCallback) -: SpecialConfigRequest(nullptr, std::move(timeCallback), QString()) { +SpecialConfigRequest::SpecialConfigRequest( + Fn callback, + const QString &phone) +: SpecialConfigRequest(std::move(callback), nullptr, phone) { +} + +SpecialConfigRequest::SpecialConfigRequest(Fn timeDoneCallback) +: SpecialConfigRequest(nullptr, std::move(timeDoneCallback), QString()) { } void SpecialConfigRequest::sendNextRequest() { @@ -326,7 +339,7 @@ void SpecialConfigRequest::performRequest(const Attempt &attempt) { void SpecialConfigRequest::handleHeaderUnixtime( not_null reply) { - if (!_timeCallback || reply->error() != QNetworkReply::NoError) { + if (reply->error() != QNetworkReply::NoError) { return; } const auto date = QString::fromLatin1([&] { @@ -346,7 +359,10 @@ void SpecialConfigRequest::handleHeaderUnixtime( LOG(("Config Error: Bad 'Date' header received: %1").arg(date)); return; } - _timeCallback(parsed.toTime_t()); + base::unixtime::http_update(parsed.toTime_t()); + if (_timeDoneCallback) { + _timeDoneCallback(); + } } void SpecialConfigRequest::requestFinished( @@ -460,9 +476,9 @@ void SpecialConfigRequest::handleResponse(const QByteArray &bytes) { return; } Assert(_simpleConfig.type() == mtpc_help_configSimple); - auto &config = _simpleConfig.c_help_configSimple(); - auto now = unixtime(); - if (now < config.vdate().v || now > config.vexpires().v) { + const auto &config = _simpleConfig.c_help_configSimple(); + const auto now = base::unixtime::now(); + if (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)); return; } diff --git a/Telegram/SourceFiles/mtproto/special_config_request.h b/Telegram/SourceFiles/mtproto/special_config_request.h index 42c732636..a6d762534 100644 --- a/Telegram/SourceFiles/mtproto/special_config_request.h +++ b/Telegram/SourceFiles/mtproto/special_config_request.h @@ -31,9 +31,8 @@ public: const std::string &ip, int port, bytes::const_span secret)> callback, - Fn timeCallback, const QString &phone); - explicit SpecialConfigRequest(Fn timeCallback); + explicit SpecialConfigRequest(Fn timeDoneCallback); private: enum class Type { @@ -45,6 +44,15 @@ private: QString domain; }; + SpecialConfigRequest( + Fn callback, + Fn timeDoneCallback, + const QString &phone); + void sendNextRequest(); void performRequest(const Attempt &attempt); void requestFinished(Type type, not_null reply); @@ -58,7 +66,7 @@ private: const std::string &ip, int port, bytes::const_span secret)> _callback; - Fn _timeCallback; + Fn _timeDoneCallback; QString _phone; MTPhelp_ConfigSimple _simpleConfig; diff --git a/Telegram/SourceFiles/overview/overview_layout.cpp b/Telegram/SourceFiles/overview/overview_layout.cpp index 61fe3e7af..211802970 100644 --- a/Telegram/SourceFiles/overview/overview_layout.cpp +++ b/Telegram/SourceFiles/overview/overview_layout.cpp @@ -27,6 +27,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "history/history_item.h" #include "history/history_item_components.h" #include "history/view/history_view_cursor_state.h" +#include "base/unixtime.h" #include "ui/effects/round_checkbox.h" #include "ui/image/image.h" #include "ui/text_options.h" @@ -591,7 +592,7 @@ Voice::Voice( const auto dateText = textcmdLink( 1, TextUtilities::EscapeForRichParsing( - langDateTime(ParseDateTime(_data->date)))); + langDateTime(base::unixtime::parse(_data->date)))); TextParseOptions opts = { TextParseRichText, 0, 0, Qt::LayoutDirectionAuto }; _details.setText( st::defaultTextStyle, @@ -871,7 +872,7 @@ Document::Document( , _msgl(goToMessageClickHandler(parent)) , _namel(std::make_shared(_data, parent->fullId())) , _st(st) -, _date(langDateTime(ParseDateTime(_data->date))) +, _date(langDateTime(base::unixtime::parse(_data->date))) , _datew(st::normalFont->width(_date)) , _colorIndex(documentColorIndex(_data, _ext)) { _name.setMarkedText(st::defaultTextStyle, ComposeNameWithEntities(_data), _documentNameOptions); diff --git a/Telegram/SourceFiles/passport/passport_form_controller.cpp b/Telegram/SourceFiles/passport/passport_form_controller.cpp index a538a5c8b..bdbda95b7 100644 --- a/Telegram/SourceFiles/passport/passport_form_controller.cpp +++ b/Telegram/SourceFiles/passport/passport_form_controller.cpp @@ -16,6 +16,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lang/lang_hardcoded.h" #include "base/openssl_help.h" #include "base/qthelp_url.h" +#include "base/unixtime.h" #include "data/data_session.h" #include "data/data_user.h" #include "mainwindow.h" @@ -1402,7 +1403,7 @@ void FormController::prepareFile( file.fields.id = fileId; file.fields.dcId = MTP::maindc(); file.fields.secret = GenerateSecretBytes(); - file.fields.date = unixtime(); + file.fields.date = base::unixtime::now(); file.fields.image = ReadImage(bytes::make_span(content)); file.fields.downloadOffset = file.fields.size; diff --git a/Telegram/SourceFiles/passport/passport_panel_controller.cpp b/Telegram/SourceFiles/passport/passport_panel_controller.cpp index 5c612adf3..8fbf26bbf 100644 --- a/Telegram/SourceFiles/passport/passport_panel_controller.cpp +++ b/Telegram/SourceFiles/passport/passport_panel_controller.cpp @@ -14,6 +14,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "passport/passport_panel_edit_scans.h" #include "passport/passport_panel.h" #include "base/openssl_help.h" +#include "base/unixtime.h" #include "boxes/passcode_box.h" #include "boxes/confirm_box.h" #include "ui/toast/toast.h" @@ -48,7 +49,8 @@ ScanInfo CollectScanInfo(const EditFile &file) { return tr::lng_passport_scan_uploaded( tr::now, lt_date, - langDateTimeFull(ParseDateTime(file.fields.date))); + langDateTimeFull( + base::unixtime::parse(file.fields.date))); } } else if (file.uploadData) { if (file.uploadData->offset < 0) { @@ -61,7 +63,8 @@ ScanInfo CollectScanInfo(const EditFile &file) { return tr::lng_passport_scan_uploaded( tr::now, lt_date, - langDateTimeFull(ParseDateTime(file.fields.date))); + langDateTimeFull( + base::unixtime::parse(file.fields.date))); } } else { return formatDownloadText(0, file.fields.size); diff --git a/Telegram/SourceFiles/profile/profile_block_group_members.cpp b/Telegram/SourceFiles/profile/profile_block_group_members.cpp index 29aa10ad8..e503d4d11 100644 --- a/Telegram/SourceFiles/profile/profile_block_group_members.cpp +++ b/Telegram/SourceFiles/profile/profile_block_group_members.cpp @@ -12,6 +12,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "boxes/confirm_box.h" #include "boxes/peers/edit_participant_box.h" #include "boxes/peers/edit_participants_box.h" +#include "base/unixtime.h" #include "ui/widgets/popup_menu.h" #include "data/data_peer_values.h" #include "data/data_channel.h" @@ -128,7 +129,7 @@ void GroupMembersWidget::refreshUserOnline(UserData *user) { auto it = _membersByUser.find(user); if (it == _membersByUser.cend()) return; - _now = unixtime(); + _now = base::unixtime::now(); auto member = getMember(it.value()); member->statusHasOnlineColor = !user->botInfo && Data::OnlineTextActive(user->onlineTill, _now); @@ -180,7 +181,7 @@ void GroupMembersWidget::updateItemStatusText(Item *item) { } void GroupMembersWidget::refreshMembers() { - _now = unixtime(); + _now = base::unixtime::now(); if (const auto chat = peer()->asChat()) { checkSelfAdmin(chat); if (chat->noParticipantInfo()) { @@ -421,7 +422,7 @@ auto GroupMembersWidget::computeMember(not_null user) void GroupMembersWidget::onUpdateOnlineDisplay() { if (_sortByOnline) { - _now = unixtime(); + _now = base::unixtime::now(); bool changed = false; for_const (auto item, items()) { diff --git a/Telegram/SourceFiles/settings/settings_privacy_controllers.cpp b/Telegram/SourceFiles/settings/settings_privacy_controllers.cpp index 601f0089e..8bbec1835 100644 --- a/Telegram/SourceFiles/settings/settings_privacy_controllers.cpp +++ b/Telegram/SourceFiles/settings/settings_privacy_controllers.cpp @@ -23,6 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "history/history_message.h" #include "history/history.h" #include "calls/calls_instance.h" +#include "base/unixtime.h" #include "ui/widgets/checkbox.h" #include "ui/wrap/padding_wrap.h" #include "ui/wrap/vertical_layout.h" @@ -125,7 +126,7 @@ AdminLog::OwnedItem GenerateForwardedItem( MTP_flags(FwdFlag::f_from_id), MTP_int(history->session().userId()), MTPstring(), // from_name - MTP_int(unixtime()), + MTP_int(base::unixtime::now()), MTPint(), // channel_id MTPint(), // channel_post MTPstring(), // post_author @@ -133,7 +134,7 @@ AdminLog::OwnedItem GenerateForwardedItem( MTPint()), // saved_from_msg_id MTPint(), // via_bot_id MTPint(), // reply_to_msg_id, - MTP_int(unixtime()), // date + MTP_int(base::unixtime::now()), // date MTP_string(text), MTPMessageMedia(), MTPReplyMarkup(), diff --git a/Telegram/SourceFiles/storage/localimageloader.cpp b/Telegram/SourceFiles/storage/localimageloader.cpp index c87e5fef8..186e0697a 100644 --- a/Telegram/SourceFiles/storage/localimageloader.cpp +++ b/Telegram/SourceFiles/storage/localimageloader.cpp @@ -11,6 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_session.h" #include "core/file_utilities.h" #include "core/mime_type.h" +#include "base/unixtime.h" #include "media/audio/media_audio.h" #include "media/clip/media_clip_reader.h" #include "lottie/lottie_animation.h" @@ -217,7 +218,7 @@ SendMediaReady PreparePeerPhoto(PeerId peerId, QImage &&image) { MTP_long(id), MTP_long(0), MTP_bytes(), - MTP_int(unixtime()), + MTP_int(base::unixtime::now()), MTP_vector(photoSizes), MTP_int(MTP::maindc())); @@ -280,7 +281,7 @@ SendMediaReady PrepareWallPaper(const QImage &image) { MTP_long(id), MTP_long(0), MTP_bytes(), - MTP_int(unixtime()), + MTP_int(base::unixtime::now()), MTP_string("image/jpeg"), MTP_int(jpeg.size()), MTP_vector(sizes), @@ -929,7 +930,7 @@ void FileLoadTask::process() { MTP_long(_id), MTP_long(0), MTP_bytes(), - MTP_int(unixtime()), + MTP_int(base::unixtime::now()), MTP_vector(photoSizes), MTP_int(MTP::maindc())); @@ -959,7 +960,7 @@ void FileLoadTask::process() { MTP_long(_id), MTP_long(0), MTP_bytes(), - MTP_int(unixtime()), + MTP_int(base::unixtime::now()), MTP_string(filemime), MTP_int(filesize), MTP_vector(1, thumbnail.mtpSize), @@ -971,7 +972,7 @@ void FileLoadTask::process() { MTP_long(_id), MTP_long(0), MTP_bytes(), - MTP_int(unixtime()), + MTP_int(base::unixtime::now()), MTP_string(filemime), MTP_int(filesize), MTP_vector(1, thumbnail.mtpSize), diff --git a/Telegram/SourceFiles/support/support_autocomplete.cpp b/Telegram/SourceFiles/support/support_autocomplete.cpp index 73b80e018..524b0764d 100644 --- a/Telegram/SourceFiles/support/support_autocomplete.cpp +++ b/Telegram/SourceFiles/support/support_autocomplete.cpp @@ -18,6 +18,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "history/history_message.h" #include "lang/lang_keys.h" #include "data/data_session.h" +#include "base/unixtime.h" #include "auth_session.h" #include "apiwrap.h" #include "styles/style_chat_helpers.h" @@ -278,7 +279,7 @@ AdminLog::OwnedItem GenerateCommentItem( flags, replyTo, viaBotId, - unixtime(), + base::unixtime::now(), history->session().userId(), QString(), TextWithEntities{ TextUtilities::Clean(data.comment) }); @@ -302,7 +303,7 @@ AdminLog::OwnedItem GenerateContactItem( MTPMessageFwdHeader(), MTP_int(viaBotId), MTP_int(replyTo), - MTP_int(unixtime()), + MTP_int(base::unixtime::now()), MTP_string(), MTP_messageMediaContact( MTP_string(data.phone), diff --git a/Telegram/SourceFiles/support/support_helper.cpp b/Telegram/SourceFiles/support/support_helper.cpp index 2e1998bc4..718fa78ea 100644 --- a/Telegram/SourceFiles/support/support_helper.cpp +++ b/Telegram/SourceFiles/support/support_helper.cpp @@ -19,6 +19,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "ui/text_options.h" #include "chat_helpers/message_field.h" #include "chat_helpers/emoji_suggestions_widget.h" +#include "base/unixtime.h" #include "lang/lang_keys.h" #include "window/window_session_controller.h" #include "storage/storage_media_prepare.h" @@ -119,7 +120,7 @@ void EditInfoBox::setInnerFocus() { QString FormatDateTime(TimeId value) { const auto now = QDateTime::currentDateTime(); - const auto date = ParseDateTime(value); + const auto date = base::unixtime::parse(value); if (date.date() == now.date()) { return tr::lng_mediaview_today( tr::now, @@ -149,7 +150,7 @@ QString NormalizeName(QString name) { } Data::Draft OccupiedDraft(const QString &normalizedName) { - const auto now = unixtime(), till = now + kOccupyFor; + const auto now = base::unixtime::now(), till = now + kOccupyFor; return { TextWithTags{ "t:" + QString::number(till) @@ -190,7 +191,7 @@ uint32 ParseOccupationTag(History *history) { auto result = uint32(); for (const auto &part : parts) { if (part.startsWith(qstr("t:"))) { - if (part.mid(2).toInt() >= unixtime()) { + if (part.mid(2).toInt() >= base::unixtime::now()) { valid = true; } else { return 0; @@ -220,7 +221,7 @@ QString ParseOccupationName(History *history) { auto result = QString(); for (const auto &part : parts) { if (part.startsWith(qstr("t:"))) { - if (part.mid(2).toInt() >= unixtime()) { + if (part.mid(2).toInt() >= base::unixtime::now()) { valid = true; } else { return 0; @@ -254,7 +255,7 @@ TimeId OccupiedBySomeoneTill(History *history) { auto result = TimeId(); for (const auto &part : parts) { if (part.startsWith(qstr("t:"))) { - if (part.mid(2).toInt() >= unixtime()) { + if (part.mid(2).toInt() >= base::unixtime::now()) { result = part.mid(2).toInt(); } else { return 0; @@ -330,7 +331,7 @@ void Helper::chatOccupiedUpdated(not_null history) { } void Helper::checkOccupiedChats() { - const auto now = unixtime(); + const auto now = base::unixtime::now(); while (!_occupiedChats.empty()) { const auto nearest = ranges::min_element( _occupiedChats, diff --git a/Telegram/SourceFiles/window/notifications_manager.cpp b/Telegram/SourceFiles/window/notifications_manager.cpp index 86be1e18a..0d492ce55 100644 --- a/Telegram/SourceFiles/window/notifications_manager.cpp +++ b/Telegram/SourceFiles/window/notifications_manager.cpp @@ -17,6 +17,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "lang/lang_keys.h" #include "data/data_session.h" #include "data/data_channel.h" +#include "base/unixtime.h" #include "window/window_session_controller.h" #include "core/application.h" #include "mainwindow.h" @@ -98,7 +99,7 @@ void System::schedule(History *history, HistoryItem *item) { } auto delay = item->Has() ? 500 : 100; - auto t = unixtime(); + auto t = base::unixtime::now(); auto ms = crl::now(); bool isOnline = App::main()->lastWasOnline(), otherNotOld = ((cOtherOnline() * 1000LL) + Global::OnlineCloudTimeout() > t * 1000LL); bool otherLaterThanMe = (cOtherOnline() * 1000LL + (ms - App::main()->lastSetOnline()) > t * 1000LL); @@ -237,7 +238,7 @@ void System::showNext() { auto ms = crl::now(), nextAlert = crl::time(0); bool alert = false; - int32 now = unixtime(); + int32 now = base::unixtime::now(); for (auto i = _whenAlerts.begin(); i != _whenAlerts.end();) { while (!i.value().isEmpty() && i.value().begin().key() <= ms) { const auto peer = i.key()->peer; diff --git a/Telegram/SourceFiles/window/window_session_controller.cpp b/Telegram/SourceFiles/window/window_session_controller.cpp index fe478febc..d04559433 100644 --- a/Telegram/SourceFiles/window/window_session_controller.cpp +++ b/Telegram/SourceFiles/window/window_session_controller.cpp @@ -22,6 +22,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL #include "data/data_chat.h" #include "passport/passport_form_controller.h" #include "core/shortcuts.h" +#include "base/unixtime.h" #include "boxes/calendar_box.h" #include "mainwidget.h" #include "mainwindow.h" @@ -492,13 +493,13 @@ void SessionController::showJumpToDate(Dialogs::Key chat, QDate requestedDate) { } } } else if (history->chatListTimeId() != 0) { - return ParseDateTime(history->chatListTimeId()).date(); + return base::unixtime::parse(history->chatListTimeId()).date(); } //} else if (const auto feed = chat.feed()) { // #feed // if (chatScrollPosition(feed)) { // #TODO feeds save position // } else if (feed->chatListTimeId() != 0) { - // return ParseDateTime(feed->chatListTimeId()).date(); + // return base::unixtime::parse(feed->chatListTimeId()).date(); // } } return QDate(); @@ -509,11 +510,11 @@ void SessionController::showJumpToDate(Dialogs::Key chat, QDate requestedDate) { history = channel->owner().historyLoaded(channel); } if (history && history->chatListTimeId() != 0) { - return ParseDateTime(history->chatListTimeId()).date(); + return base::unixtime::parse(history->chatListTimeId()).date(); } //} else if (const auto feed = chat.feed()) { // #feed // if (feed->chatListTimeId() != 0) { - // return ParseDateTime(feed->chatListTimeId()).date(); + // return base::unixtime::parse(feed->chatListTimeId()).date(); // } } return QDate::currentDate(); diff --git a/Telegram/gyp/lib_base.gyp b/Telegram/gyp/lib_base.gyp index c4b9d567d..82d42d4ae 100644 --- a/Telegram/gyp/lib_base.gyp +++ b/Telegram/gyp/lib_base.gyp @@ -80,6 +80,8 @@ '<(src_loc)/base/unique_any.h', '<(src_loc)/base/unique_function.h', '<(src_loc)/base/unique_qptr.h', + '<(src_loc)/base/unixtime.cpp', + '<(src_loc)/base/unixtime.h', '<(src_loc)/base/value_ordering.h', '<(src_loc)/base/variant.h', '<(src_loc)/base/virtual_method.h',