Fix possible race conditions in msgid().

This commit is contained in:
John Preston 2019-07-10 19:28:33 +02:00
parent 68b1024dd4
commit c5df4db621
63 changed files with 513 additions and 391 deletions

View File

@ -24,6 +24,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/core_cloud_password.h" #include "core/core_cloud_password.h"
#include "core/application.h" #include "core/application.h"
#include "base/openssl_help.h" #include "base/openssl_help.h"
#include "base/unixtime.h"
#include "observer_peer.h" #include "observer_peer.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "mainwindow.h" #include "mainwindow.h"
@ -259,7 +260,7 @@ void ApiWrap::setupSupportMode() {
_session->settings().supportChatsTimeSliceValue( _session->settings().supportChatsTimeSliceValue(
) | rpl::start_with_next([=](int seconds) { ) | 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(); refreshDialogsLoadBlocked();
}, _session->lifetime()); }, _session->lifetime());
} }
@ -275,7 +276,7 @@ void ApiWrap::requestChangelog(
} }
void ApiWrap::refreshProxyPromotion() { void ApiWrap::refreshProxyPromotion() {
const auto now = unixtime(); const auto now = base::unixtime::now();
const auto next = (_proxyPromotionNextRequestTime != 0) const auto next = (_proxyPromotionNextRequestTime != 0)
? _proxyPromotionNextRequestTime ? _proxyPromotionNextRequestTime
: now; : now;
@ -300,7 +301,7 @@ void ApiWrap::refreshProxyPromotion() {
_proxyPromotionKey = key; _proxyPromotionKey = key;
if (key.first.isEmpty() || !key.second) { if (key.first.isEmpty() || !key.second) {
proxyPromotionDone(MTP_help_proxyDataEmpty( proxyPromotionDone(MTP_help_proxyDataEmpty(
MTP_int(unixtime() + kProxyPromotionInterval))); MTP_int(base::unixtime::now() + kProxyPromotionInterval)));
return; return;
} }
_proxyPromotionRequestId = request(MTPhelp_GetProxyData( _proxyPromotionRequestId = request(MTPhelp_GetProxyData(
@ -309,7 +310,7 @@ void ApiWrap::refreshProxyPromotion() {
proxyPromotionDone(result); proxyPromotionDone(result);
}).fail([=](const RPCError &error) { }).fail([=](const RPCError &error) {
_proxyPromotionRequestId = 0; _proxyPromotionRequestId = 0;
const auto now = unixtime(); const auto now = base::unixtime::now();
const auto next = _proxyPromotionNextRequestTime = now const auto next = _proxyPromotionNextRequestTime = now
+ kProxyPromotionInterval; + kProxyPromotionInterval;
if (!_proxyPromotionTimer.isActive()) { if (!_proxyPromotionTimer.isActive()) {
@ -328,7 +329,7 @@ void ApiWrap::proxyPromotionDone(const MTPhelp_ProxyData &proxy) {
_proxyPromotionNextRequestTime = proxy.match([&](const auto &data) { _proxyPromotionNextRequestTime = proxy.match([&](const auto &data) {
return data.vexpires().v; return data.vexpires().v;
}); });
getProxyPromotionDelayed(unixtime(), _proxyPromotionNextRequestTime); getProxyPromotionDelayed(base::unixtime::now(), _proxyPromotionNextRequestTime);
proxy.match([&](const MTPDhelp_proxyDataEmpty &data) { proxy.match([&](const MTPDhelp_proxyDataEmpty &data) {
_session->data().setProxyPromoted(nullptr); _session->data().setProxyPromoted(nullptr);
@ -380,7 +381,7 @@ void ApiWrap::requestTermsUpdate() {
_termsUpdateRequestId = 0; _termsUpdateRequestId = 0;
const auto requestNext = [&](auto &&data) { 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( _termsUpdateSendAt = crl::now() + snap(
timeout * crl::time(1000), timeout * crl::time(1000),
kTermsUpdateTimeoutMin, kTermsUpdateTimeoutMin,
@ -966,7 +967,7 @@ void ApiWrap::requestMoreBlockedByDateDialogs() {
const auto max = _session->settings().supportChatsTimeSlice(); const auto max = _session->settings().supportChatsTimeSlice();
_dialogsLoadTill = _dialogsLoadState->offsetDate _dialogsLoadTill = _dialogsLoadState->offsetDate
? (_dialogsLoadState->offsetDate - max) ? (_dialogsLoadState->offsetDate - max)
: (unixtime() - max); : (base::unixtime::now() - max);
refreshDialogsLoadBlocked(); refreshDialogsLoadBlocked();
requestDialogs(); requestDialogs();
} }
@ -2120,7 +2121,7 @@ void ApiWrap::saveStickerSets(
order.push_back(setId); order.push_back(setId);
it->flags |= MTPDstickerSet::Flag::f_installed_date; it->flags |= MTPDstickerSet::Flag::f_installed_date;
if (!it->installDate) { if (!it->installDate) {
it->installDate = unixtime(); it->installDate = base::unixtime::now();
} }
} }
} }
@ -2215,7 +2216,7 @@ void ApiWrap::blockUser(not_null<UserData*> user) {
if (_blockedUsersSlice) { if (_blockedUsersSlice) {
_blockedUsersSlice->list.insert( _blockedUsersSlice->list.insert(
_blockedUsersSlice->list.begin(), _blockedUsersSlice->list.begin(),
{ user, unixtime() }); { user, base::unixtime::now() });
++_blockedUsersSlice->total; ++_blockedUsersSlice->total;
_blockedUsersChanges.fire_copy(*_blockedUsersSlice); _blockedUsersChanges.fire_copy(*_blockedUsersSlice);
} }
@ -2401,7 +2402,7 @@ void ApiWrap::handlePrivacyChange(
} }
void ApiWrap::updatePrivacyLastSeens(const QVector<MTPPrivacyRule> &rules) { void ApiWrap::updatePrivacyLastSeens(const QVector<MTPPrivacyRule> &rules) {
const auto now = unixtime(); const auto now = base::unixtime::now();
_session->data().enumerateUsers([&](UserData *user) { _session->data().enumerateUsers([&](UserData *user) {
if (user->isSelf() || user->loadedStatus != PeerData::FullLoaded) { if (user->isSelf() || user->loadedStatus != PeerData::FullLoaded) {
return; return;
@ -2734,7 +2735,7 @@ void ApiWrap::gotStickerSet(uint64 setId, const MTPmessages_StickerSet &result)
void ApiWrap::requestWebPageDelayed(WebPageData *page) { void ApiWrap::requestWebPageDelayed(WebPageData *page) {
if (page->pendingTill <= 0) return; if (page->pendingTill <= 0) return;
_webPagesPending.insert(page, 0); _webPagesPending.insert(page, 0);
auto left = (page->pendingTill - unixtime()) * 1000; auto left = (page->pendingTill - base::unixtime::now()) * 1000;
if (!_webPagesTimer.isActive() || left <= _webPagesTimer.remainingTime()) { if (!_webPagesTimer.isActive() || left <= _webPagesTimer.remainingTime()) {
_webPagesTimer.callOnce((left < 0 ? 0 : left) + 1); _webPagesTimer.callOnce((left < 0 ? 0 : left) + 1);
} }
@ -2759,7 +2760,7 @@ void ApiWrap::resolveWebPages() {
MessageIdsByChannel idsByChannel; // temp_req_id = -index - 2 MessageIdsByChannel idsByChannel; // temp_req_id = -index - 2
ids.reserve(_webPagesPending.size()); 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) { for (auto i = _webPagesPending.begin(); i != _webPagesPending.cend(); ++i) {
if (i.value() > 0) continue; if (i.value() > 0) continue;
if (i.key()->pendingTill <= t) { if (i.key()->pendingTill <= t) {
@ -3675,7 +3676,7 @@ void ApiWrap::applyUpdateNoPtsCheck(const MTPUpdate &update) {
if (item->out() if (item->out()
&& item->history()->peer->isUser() && item->history()->peer->isUser()
&& !App::main()->requestingDifference()) { && !App::main()->requestingDifference()) {
item->history()->peer->asUser()->madeAction(unixtime()); item->history()->peer->asUser()->madeAction(base::unixtime::now());
} }
} }
} else { } else {
@ -3705,7 +3706,7 @@ void ApiWrap::applyUpdateNoPtsCheck(const MTPUpdate &update) {
history->outboxRead(d.vmax_id().v); history->outboxRead(d.vmax_id().v);
if (!App::main()->requestingDifference()) { if (!App::main()->requestingDifference()) {
if (const auto user = history->peer->asUser()) { if (const auto user = history->peer->asUser()) {
user->madeAction(unixtime()); user->madeAction(base::unixtime::now());
} }
} }
} }
@ -4510,7 +4511,7 @@ void ApiWrap::forwardMessages(
history->addNewForwarded( history->addNewForwarded(
newId.msg, newId.msg,
flags, flags,
unixtime(), base::unixtime::now(),
messageFromId, messageFromId,
messagePostAuthor, messagePostAuthor,
message); message);
@ -4599,7 +4600,7 @@ void ApiWrap::sendSharedContact(
MTPMessageFwdHeader(), MTPMessageFwdHeader(),
MTPint(), MTPint(),
MTP_int(options.replyTo), MTP_int(options.replyTo),
MTP_int(unixtime()), MTP_int(base::unixtime::now()),
MTP_string(), MTP_string(),
MTP_messageMediaContact( MTP_messageMediaContact(
MTP_string(phone), MTP_string(phone),
@ -4981,7 +4982,7 @@ void ApiWrap::sendMessage(MessageToSend &&message) {
MTPMessageFwdHeader(), MTPMessageFwdHeader(),
MTPint(), MTPint(),
MTP_int(message.replyTo), MTP_int(message.replyTo),
MTP_int(unixtime()), MTP_int(base::unixtime::now()),
msgText, msgText,
media, media,
MTPReplyMarkup(), MTPReplyMarkup(),
@ -5089,7 +5090,7 @@ void ApiWrap::sendInlineResult(
auto messagePostAuthor = channelPost auto messagePostAuthor = channelPost
? App::peerName(_session->user()) ? App::peerName(_session->user())
: QString(); : QString();
MTPint messageDate = MTP_int(unixtime()); MTPint messageDate = MTP_int(base::unixtime::now());
UserId messageViaBotId = bot ? peerToUser(bot->id) : 0; UserId messageViaBotId = bot ? peerToUser(bot->id) : 0;
MsgId messageId = newId.msg; MsgId messageId = newId.msg;
@ -5184,7 +5185,7 @@ void ApiWrap::sendExistingDocument(
flags, flags,
0, 0,
replyTo, replyTo,
unixtime(), base::unixtime::now(),
messageFromId, messageFromId,
messagePostAuthor, messagePostAuthor,
document, document,

View File

@ -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 <QDateTime>
#include <QReadWriteLock>
#ifdef Q_OS_WIN
#elif defined Q_OS_MAC
#include <mach/mach_time.h>
#else
#include <time.h>
#endif
namespace base {
namespace unixtime {
namespace {
std::atomic<bool> ValueUpdated/* = false*/;
std::atomic<TimeId> ValueShift/* = 0*/;
std::atomic<bool> HttpValueValid/* = false*/;
std::atomic<TimeId> HttpValueShift/* = 0*/;
class MsgIdManager {
public:
MsgIdManager();
void update();
[[nodiscard]] uint64 next();
private:
void initialize();
QReadWriteLock _lock;
uint64 _startId = 0;
std::atomic<uint32> _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<uint32>();
_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

View File

@ -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

View File

@ -21,6 +21,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_session.h" #include "data/data_session.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "data/data_document.h" #include "data/data_document.h"
#include "base/unixtime.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "boxes/background_preview_box.h" #include "boxes/background_preview_box.h"
#include "styles/style_history.h" #include "styles/style_history.h"
@ -291,7 +292,7 @@ AdminLog::OwnedItem GenerateTextItem(
flags, flags,
replyTo, replyTo,
viaBotId, viaBotId,
unixtime(), base::unixtime::now(),
out ? history->session().userId() : peerToUser(history->peer->id), out ? history->session().userId() : peerToUser(history->peer->id),
QString(), QString(),
TextWithEntities{ TextUtilities::Clean(text) }); TextWithEntities{ TextUtilities::Clean(text) });

View File

@ -30,6 +30,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_channel.h" #include "data/data_channel.h"
#include "data/data_chat.h" #include "data/data_chat.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "base/unixtime.h"
#include "auth_session.h" #include "auth_session.h"
#include "observer_peer.h" #include "observer_peer.h"
@ -620,7 +621,7 @@ auto DeleteMessagesBox::revokeText(not_null<PeerData*> peer) const
return std::nullopt; return std::nullopt;
} }
const auto now = unixtime(); const auto now = base::unixtime::now();
const auto canRevoke = [&](HistoryItem * item) { const auto canRevoke = [&](HistoryItem * item) {
return item->canDeleteForEveryone(now); return item->canDeleteForEveryone(now);
}; };

View File

@ -28,6 +28,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_peer_values.h" #include "data/data_peer_values.h"
#include "data/data_chat.h" #include "data/data_chat.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "base/unixtime.h"
#include "window/themes/window_theme.h" #include "window/themes/window_theme.h"
auto PaintUserpicCallback( auto PaintUserpicCallback(
@ -57,7 +58,7 @@ void PeerListBox::createMultiSelect() {
Expects(_select == nullptr); Expects(_select == nullptr);
auto entity = object_ptr<Ui::MultiSelect>( auto entity = object_ptr<Ui::MultiSelect>(
this, this,
st::contactsMultiSelect, st::contactsMultiSelect,
tr::lng_participant_filter()); tr::lng_participant_filter());
_select.create(this, std::move(entity)); _select.create(this, std::move(entity));
@ -377,7 +378,7 @@ void PeerListRow::refreshStatus() {
if (_isSavedMessagesChat) { if (_isSavedMessagesChat) {
setStatusText(tr::lng_saved_forward_here(tr::now)); setStatusText(tr::lng_saved_forward_here(tr::now));
} else { } else {
auto time = unixtime(); auto time = base::unixtime::now();
setStatusText(Data::OnlineText(user, time)); setStatusText(Data::OnlineText(user, time));
if (Data::OnlineTextActive(user, time)) { if (Data::OnlineTextActive(user, time)) {
_statusType = StatusType::Online; _statusType = StatusType::Online;

View File

@ -17,6 +17,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_folder.h" #include "data/data_folder.h"
#include "history/history.h" #include "history/history.h"
#include "dialogs/dialogs_indexed_list.h" #include "dialogs/dialogs_indexed_list.h"
#include "base/unixtime.h"
#include "auth_session.h" #include "auth_session.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "mainwindow.h" #include "mainwindow.h"
@ -575,7 +576,7 @@ void AddSpecialBoxController::editAdminDone(
_editParticipantBox->closeBox(); _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) { if (rights.c_chatAdminRights().vflags().v == 0) {
_additional.applyParticipant(MTP_channelParticipant( _additional.applyParticipant(MTP_channelParticipant(
MTP_int(user->bareId()), MTP_int(user->bareId()),
@ -672,7 +673,7 @@ void AddSpecialBoxController::editRestrictedDone(
_editParticipantBox->closeBox(); _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) { if (rights.c_chatBannedRights().vflags().v == 0) {
_additional.applyParticipant(MTP_channelParticipant( _additional.applyParticipant(MTP_channelParticipant(
MTP_int(user->bareId()), MTP_int(user->bareId()),

View File

@ -31,6 +31,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_chat.h" #include "data/data_chat.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "core/core_cloud_password.h" #include "core/core_cloud_password.h"
#include "base/unixtime.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "auth_session.h" #include "auth_session.h"
#include "styles/style_boxes.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_reads_all
: tr::lng_status_bot_not_reads_all)(tr::now); : 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.setFont(st::contactsStatusFont);
p.setPen(st::contactsStatusFg); p.setPen(st::contactsStatusFg);
@ -678,7 +679,7 @@ void EditRestrictedBox::showRestrictUntil() {
auto tomorrow = QDate::currentDate().addDays(1); auto tomorrow = QDate::currentDate().addDays(1);
auto highlighted = isUntilForever() auto highlighted = isUntilForever()
? tomorrow ? tomorrow
: ParseDateTime(getRealUntilValue()).date(); : base::unixtime::parse(getRealUntilValue()).date();
auto month = highlighted; auto month = highlighted;
_restrictUntilBox = Ui::show( _restrictUntilBox = Ui::show(
Box<CalendarBox>( Box<CalendarBox>(
@ -751,7 +752,8 @@ void EditRestrictedBox::createUntilVariants() {
tr::lng_rights_chat_banned_custom_date( tr::lng_rights_chat_banned_custom_date(
tr::now, tr::now,
lt_date, lt_date,
langDayOfMonthFull(ParseDateTime(until).date()))); langDayOfMonthFull(
base::unixtime::parse(until).date())));
} }
}; };
auto addCurrentVariant = [&](TimeId from, TimeId to) { auto addCurrentVariant = [&](TimeId from, TimeId to) {
@ -766,7 +768,7 @@ void EditRestrictedBox::createUntilVariants() {
}; };
addVariant(0, tr::lng_rights_chat_banned_forever(tr::now)); addVariant(0, tr::lng_rights_chat_banned_forever(tr::now));
auto now = unixtime(); auto now = base::unixtime::now();
auto nextDay = now + kSecondsInDay; auto nextDay = now + kSecondsInDay;
auto nextWeek = now + kSecondsInWeek; auto nextWeek = now + kSecondsInWeek;
addCurrentVariant(0, nextDay); addCurrentVariant(0, nextDay);
@ -780,9 +782,9 @@ void EditRestrictedBox::createUntilVariants() {
TimeId EditRestrictedBox::getRealUntilValue() const { TimeId EditRestrictedBox::getRealUntilValue() const {
Expects(_until != kUntilCustom); Expects(_until != kUntilCustom);
if (_until == kUntilOneDay) { if (_until == kUntilOneDay) {
return unixtime() + kSecondsInDay; return base::unixtime::now() + kSecondsInDay;
} else if (_until == kUntilOneWeek) { } else if (_until == kUntilOneWeek) {
return unixtime() + kSecondsInWeek; return base::unixtime::now() + kSecondsInWeek;
} }
Assert(_until >= 0); Assert(_until >= 0);
return _until; return _until;

View File

@ -23,6 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_channel.h" #include "data/data_channel.h"
#include "data/data_chat.h" #include "data/data_chat.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "base/unixtime.h"
#include "ui/widgets/popup_menu.h" #include "ui/widgets/popup_menu.h"
#include "window/window_session_controller.h" #include "window/window_session_controller.h"
#include "history/history.h" #include "history/history.h"
@ -671,7 +672,7 @@ void ParticipantsOnlineSorter::sort() {
_onlineCount = 0; _onlineCount = 0;
return; return;
} }
const auto now = unixtime(); const auto now = base::unixtime::now();
_delegate->peerListSortRows([&]( _delegate->peerListSortRows([&](
const PeerListRow &a, const PeerListRow &a,
const PeerListRow &b) { const PeerListRow &b) {
@ -686,7 +687,7 @@ rpl::producer<int> ParticipantsOnlineSorter::onlineCountValue() const {
} }
void ParticipantsOnlineSorter::refreshOnlineCount() { void ParticipantsOnlineSorter::refreshOnlineCount() {
const auto now = unixtime(); const auto now = base::unixtime::now();
auto left = 0, right = _delegate->peerListFullRowsCount(); auto left = 0, right = _delegate->peerListFullRowsCount();
while (right > left) { while (right > left) {
const auto middle = (left + right) / 2; const auto middle = (left + right) / 2;
@ -1441,7 +1442,7 @@ void ParticipantsBoxController::editAdminDone(
_editParticipantBox->closeBox(); _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) { if (rights.c_chatAdminRights().vflags().v == 0) {
_additional.applyParticipant(MTP_channelParticipant( _additional.applyParticipant(MTP_channelParticipant(
MTP_int(user->bareId()), MTP_int(user->bareId()),
@ -1509,7 +1510,7 @@ void ParticipantsBoxController::editRestrictedDone(
_editParticipantBox->closeBox(); _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) { if (rights.c_chatBannedRights().vflags().v == 0) {
_additional.applyParticipant(MTP_channelParticipant( _additional.applyParticipant(MTP_channelParticipant(
MTP_int(user->bareId()), MTP_int(user->bareId()),

View File

@ -13,6 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mainwindow.h" #include "mainwindow.h"
#include "auth_session.h" #include "auth_session.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "base/unixtime.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "info/profile/info_profile_button.h" #include "info/profile/info_profile_button.h"
#include "settings/settings_common.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)); result.activeWidth = st::sessionWhenFont->width(tr::lng_status_online(tr::now));
} else { } else {
const auto now = QDateTime::currentDateTime(); 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 nowDate = now.date();
const auto lastDate = lastTime.date(); const auto lastDate = lastTime.date();
if (lastDate == nowDate) { if (lastDate == nowDate) {

View File

@ -24,6 +24,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lottie/lottie_multi_player.h" #include "lottie/lottie_multi_player.h"
#include "lottie/lottie_animation.h" #include "lottie/lottie_animation.h"
#include "window/window_session_controller.h" #include "window/window_session_controller.h"
#include "base/unixtime.h"
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "mainwidget.h" #include "mainwidget.h"
@ -342,7 +343,7 @@ void StickerSetBox::Inner::installDone(
Auth().data().archivedStickerSetsOrderRef().removeAt(index); Auth().data().archivedStickerSetsOrderRef().removeAt(index);
} }
} }
_setInstallDate = unixtime(); _setInstallDate = base::unixtime::now();
_setFlags &= ~MTPDstickerSet::Flag::f_archived; _setFlags &= ~MTPDstickerSet::Flag::f_archived;
_setFlags |= MTPDstickerSet::Flag::f_installed_date; _setFlags |= MTPDstickerSet::Flag::f_installed_date;
auto it = sets.find(_setId); auto it = sets.find(_setId);

View File

@ -19,6 +19,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_session.h" #include "data/data_session.h"
#include "media/audio/media_audio_track.h" #include "media/audio/media_audio_track.h"
#include "platform/platform_specific.h" #include "platform/platform_specific.h"
#include "base/unixtime.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "boxes/rate_call_box.h" #include "boxes/rate_call_box.h"
@ -249,7 +250,8 @@ void Instance::handleCallUpdate(const MTPPhoneCall &call) {
MTP_phoneCallDiscardReasonBusy(), MTP_phoneCallDiscardReasonBusy(),
MTP_long(0) MTP_long(0)
)).send(); )).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.")); LOG(("Ignoring too old call."));
} else { } else {
createCall(user, Call::Type::Incoming); createCall(user, Call::Type::Incoming);

View File

@ -20,6 +20,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/image/image.h" #include "ui/image/image.h"
#include "auth_session.h" #include "auth_session.h"
#include "chat_helpers/stickers.h" #include "chat_helpers/stickers.h"
#include "base/unixtime.h"
#include "styles/style_history.h" #include "styles/style_history.h"
#include "styles/style_widgets.h" #include "styles/style_widgets.h"
#include "styles/style_chat_helpers.h" #include "styles/style_chat_helpers.h"
@ -183,7 +184,7 @@ internal::StickerRows FieldAutocomplete::getStickerSuggestions() {
} }
void FieldAutocomplete::updateFiltered(bool resetScroll) { void FieldAutocomplete::updateFiltered(bool resetScroll) {
int32 now = unixtime(), recentInlineBots = 0; int32 now = base::unixtime::now(), recentInlineBots = 0;
internal::MentionRows mrows; internal::MentionRows mrows;
internal::HashtagRows hrows; internal::HashtagRows hrows;
internal::BotCommandRows brows; internal::BotCommandRows brows;

View File

@ -19,6 +19,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mainwindow.h" #include "mainwindow.h"
#include "ui/toast/toast.h" #include "ui/toast/toast.h"
#include "ui/emoji_config.h" #include "ui/emoji_config.h"
#include "base/unixtime.h"
#include "lottie/lottie_single_player.h" #include "lottie/lottie_single_player.h"
#include "lottie/lottie_multi_player.h" #include "lottie/lottie_multi_player.h"
#include "styles/style_chat_helpers.h" #include "styles/style_chat_helpers.h"
@ -126,7 +127,7 @@ void InstallLocally(uint64 setId) {
auto flags = it->flags; auto flags = it->flags;
it->flags &= ~(MTPDstickerSet::Flag::f_archived | MTPDstickerSet_ClientFlag::f_unread); it->flags &= ~(MTPDstickerSet::Flag::f_archived | MTPDstickerSet_ClientFlag::f_unread);
it->flags |= MTPDstickerSet::Flag::f_installed_date; it->flags |= MTPDstickerSet::Flag::f_installed_date;
it->installDate = unixtime(); it->installDate = base::unixtime::now();
auto changedFlags = flags ^ it->flags; auto changedFlags = flags ^ it->flags;
auto &order = Auth().data().stickerSetsOrderRef(); auto &order = Auth().data().stickerSetsOrderRef();
@ -922,7 +923,7 @@ Set *FeedSet(const MTPDstickerSet &set) {
it->flags = set.vflags().v | clientFlags; it->flags = set.vflags().v | clientFlags;
const auto installDate = set.vinstalled_date(); const auto installDate = set.vinstalled_date();
it->installDate = installDate it->installDate = installDate
? (installDate->v ? installDate->v : unixtime()) ? (installDate->v ? installDate->v : base::unixtime::now())
: TimeId(0); : TimeId(0);
it->thumbnail = thumbnail; it->thumbnail = thumbnail;
if (it->count != set.vcount().v if (it->count != set.vcount().v

View File

@ -13,6 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_user.h" #include "data/data_user.h"
#include "base/timer.h" #include "base/timer.h"
#include "base/concurrent_timer.h" #include "base/concurrent_timer.h"
#include "base/unixtime.h"
#include "core/update_checker.h" #include "core/update_checker.h"
#include "core/shortcuts.h" #include "core/shortcuts.h"
#include "core/sandbox.h" #include "core/sandbox.h"
@ -692,6 +693,7 @@ void Application::checkLocalTime() {
if (crl::adjust_time()) { if (crl::adjust_time()) {
base::Timer::Adjust(); base::Timer::Adjust();
base::ConcurrentTimerEnvironment::Adjust(); base::ConcurrentTimerEnvironment::Adjust();
base::unixtime::http_invalidate();
if (App::main()) App::main()->checkLastUpdate(true); if (App::main()) App::main()->checkLastUpdate(true);
} else { } else {
if (App::main()) App::main()->checkLastUpdate(false); if (App::main()) App::main()->checkLastUpdate(false);

View File

@ -10,6 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "platform/platform_file_utilities.h" #include "platform/platform_file_utilities.h"
#include "core/application.h" #include "core/application.h"
#include "base/unixtime.h"
#include "mainwindow.h" #include "mainwindow.h"
bool filedialogGetSaveFile( bool filedialogGetSaveFile(
@ -62,7 +63,7 @@ QString filedialogDefaultName(
QString base; QString base;
if (fileTime) { if (fileTime) {
const auto date = ParseDateTime(fileTime); const auto date = base::unixtime::parse(fileTime);
base = prefix + date.toString("_yyyy-MM-dd_HH-mm-ss"); base = prefix + date.toString("_yyyy-MM-dd_HH-mm-ss");
} else { } else {
struct tm tm; struct tm tm;

View File

@ -118,8 +118,10 @@ void ComputeInstallationTag() {
file.close(); file.close();
} }
if (!InstallationTag) { if (!InstallationTag) {
auto generator = std::mt19937(std::random_device()());
auto distribution = std::uniform_int_distribution<uint64>();
do { do {
memsetrnd_bad(InstallationTag); InstallationTag = distribution(generator);
} while (!InstallationTag); } while (!InstallationTag);
if (file.open(QIODevice::WriteOnly)) { if (file.open(QIODevice::WriteOnly)) {

View File

@ -10,6 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "platform/platform_info.h" #include "platform/platform_info.h"
#include "base/timer.h" #include "base/timer.h"
#include "base/bytes.h" #include "base/bytes.h"
#include "base/unixtime.h"
#include "storage/localstorage.h" #include "storage/localstorage.h"
#include "core/application.h" #include "core/application.h"
#include "mainwindow.h" #include "mainwindow.h"
@ -634,7 +635,7 @@ void HttpChecker::gotResponse() {
return; return;
} }
cSetLastUpdateCheck(unixtime()); cSetLastUpdateCheck(base::unixtime::now());
const auto response = _reply->readAll(); const auto response = _reply->readAll();
clearSentRequest(); clearSentRequest();
@ -1134,7 +1135,7 @@ void Updater::handleReady() {
stop(); stop();
_action = Action::Ready; _action = Action::Ready;
if (!App::quitting()) { if (!App::quitting()) {
cSetLastUpdateCheck(unixtime()); cSetLastUpdateCheck(base::unixtime::now());
Local::writeSettings(); Local::writeSettings();
} }
} }
@ -1162,7 +1163,7 @@ void Updater::handleProgress() {
void Updater::scheduleNext() { void Updater::scheduleNext() {
stop(); stop();
if (!App::quitting()) { if (!App::quitting()) {
cSetLastUpdateCheck(unixtime()); cSetLastUpdateCheck(base::unixtime::now());
Local::writeSettings(); Local::writeSettings();
start(true); start(true);
} }
@ -1208,7 +1209,7 @@ void Updater::start(bool forceWait) {
const auto updateInSecs = cLastUpdateCheck() const auto updateInSecs = cLastUpdateCheck()
+ constDelay + constDelay
+ int(rand() % randDelay) + int(rand() % randDelay)
- unixtime(); - base::unixtime::now();
auto sendRequest = (updateInSecs <= 0) auto sendRequest = (updateInSecs <= 0)
|| (updateInSecs > constDelay + randDelay); || (updateInSecs > constDelay + randDelay);
if (!sendRequest && !forceWait) { if (!sendRequest && !forceWait) {

View File

@ -56,35 +56,10 @@ static_assert(sizeof(MTPdouble) == 8, "Basic types size check failed");
static_assert(sizeof(int) >= 4, "Basic types size check failed"); static_assert(sizeof(int) >= 4, "Basic types size check failed");
// Unixtime functions
namespace { namespace {
std::atomic<int> GlobalAtomicRequestId = 0; std::atomic<int> 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) { [[nodiscard]] bool IsHexMtprotoPassword(const QString &password) {
const auto size = password.size(); const auto size = password.size();
if (size < 32 || size % 2 == 1) { if (size < 32 || size % 2 == 1) {
@ -208,58 +183,6 @@ void _initMsgIdConstants() {
} // namespace } // 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 // Precise timing functions / rand init
struct CRYPTO_dynlock_value { struct CRYPTO_dynlock_value {
@ -320,38 +243,6 @@ namespace {
} }
return 0; 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<crl::time>(ts.tv_sec) + (static_cast<crl::time>(ts.tv_nsec) / 1000000LL);
#endif
srand((uint32)(seed & 0xFFFFFFFFL));
}
};
_MsStarter _msStarter;
} }
bool ProxyData::valid() const { 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() { int GetNextRequestId() {
const auto result = ++GlobalAtomicRequestId; const auto result = ++GlobalAtomicRequestId;
if (result == std::numeric_limits<int>::max() / 2) { if (result == std::numeric_limits<int>::max() / 2) {

View File

@ -95,15 +95,8 @@ inline QByteArray str_const_toByteArray(const str_const &str) {
return QByteArray::fromRawData(str.c_str(), str.size()); return QByteArray::fromRawData(str.c_str(), str.size());
} }
void unixtimeInit();
void unixtimeSet(TimeId serverTime, bool force = false);
TimeId unixtime();
uint64 msgid();
int GetNextRequestId(); int GetNextRequestId();
QDateTime ParseDateTime(TimeId serverTime);
TimeId ServerTimeFromParsed(const QDateTime &date);
inline void mylocaltime(struct tm * _Tm, const time_t * _Time) { inline void mylocaltime(struct tm * _Tm, const time_t * _Time) {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
localtime_s(_Tm, _Time); localtime_s(_Tm, _Time);
@ -183,17 +176,6 @@ T rand_value() {
return result; return result;
} }
inline void memset_rand_bad(void *data, uint32 len) {
for (uchar *i = reinterpret_cast<uchar*>(data), *e = i + len; i != e; ++i) {
*i = uchar(rand() & 0xFF);
}
}
template <typename T>
inline void memsetrnd_bad(T &value) {
memset_rand_bad(&value, sizeof(value));
}
class ReadLockerAttempt { class ReadLockerAttempt {
public: public:
ReadLockerAttempt(not_null<QReadWriteLock*> lock) : _lock(lock), _locked(_lock->tryLockForRead()) { ReadLockerAttempt(not_null<QReadWriteLock*> lock) : _lock(lock), _locked(_lock->tryLockForRead()) {

View File

@ -7,6 +7,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/ */
#include "data/data_notify_settings.h" #include "data/data_notify_settings.h"
#include "base/unixtime.h"
namespace Data { namespace Data {
namespace { namespace {
@ -71,7 +73,7 @@ bool NotifySettingsValue::change(const MTPDpeerNotifySettings &data) {
bool NotifySettingsValue::change( bool NotifySettingsValue::change(
std::optional<int> muteForSeconds, std::optional<int> muteForSeconds,
std::optional<bool> silentPosts) { std::optional<bool> silentPosts) {
const auto now = unixtime(); const auto now = base::unixtime::now();
const auto notMuted = muteForSeconds const auto notMuted = muteForSeconds
? !(*muteForSeconds) ? !(*muteForSeconds)
: (!_mute || *_mute <= now); : (!_mute || *_mute <= now);
@ -170,13 +172,13 @@ bool NotifySettings::change(
const auto flags = (muteForSeconds ? Flag::f_mute_until : Flag(0)) const auto flags = (muteForSeconds ? Flag::f_mute_until : Flag(0))
| (silentPosts ? Flag::f_silent : Flag(0)); | (silentPosts ? Flag::f_silent : Flag(0));
const auto muteUntil = muteForSeconds const auto muteUntil = muteForSeconds
? (unixtime() + *muteForSeconds) ? (base::unixtime::now() + *muteForSeconds)
: 0; : 0;
return change(MTP_peerNotifySettings( return change(MTP_peerNotifySettings(
MTP_flags(flags), MTP_flags(flags),
MTPBool(), MTPBool(),
silentPosts ? MTP_bool(*silentPosts) : MTPBool(), silentPosts ? MTP_bool(*silentPosts) : MTPBool(),
muteForSeconds ? MTP_int(unixtime() + *muteForSeconds) : MTPint(), muteForSeconds ? MTP_int(base::unixtime::now() + *muteForSeconds) : MTPint(),
MTPstring())); MTPstring()));
} }

View File

@ -11,6 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_channel.h" #include "data/data_channel.h"
#include "data/data_chat.h" #include "data/data_chat.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "base/unixtime.h"
namespace Data { namespace Data {
namespace { namespace {
@ -37,7 +38,7 @@ int OnlinePhraseChangeInSeconds(TimeId online, TimeId now) {
if (hours < 12) { if (hours < 12) {
return (hours + 1) * 3600 - (now - online); 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)); const auto tomorrow = QDateTime(nowFull.date().addDays(1));
return std::max(static_cast<TimeId>(nowFull.secsTo(tomorrow)), 0); return std::max(static_cast<TimeId>(nowFull.secsTo(tomorrow)), 0);
} }
@ -305,8 +306,8 @@ QString OnlineText(TimeId online, TimeId now) {
if (hours < 12) { if (hours < 12) {
return tr::lng_status_lastseen_hours(tr::now, lt_count, hours); return tr::lng_status_lastseen_hours(tr::now, lt_count, hours);
} }
const auto onlineFull = ParseDateTime(online); const auto onlineFull = base::unixtime::parse(online);
const auto nowFull = ParseDateTime(now); const auto nowFull = base::unixtime::parse(now);
if (onlineFull.date() == nowFull.date()) { if (onlineFull.date() == nowFull.date()) {
const auto onlineTime = onlineFull.time().toString(cTimeFormat()); const auto onlineTime = onlineFull.time().toString(cTimeFormat());
return tr::lng_status_lastseen_today(tr::now, lt_time, onlineTime); return tr::lng_status_lastseen_today(tr::now, lt_time, onlineTime);
@ -331,8 +332,8 @@ QString OnlineTextFull(not_null<UserData*> user, TimeId now) {
} else if (const auto common = OnlineTextCommon(user->onlineTill, now)) { } else if (const auto common = OnlineTextCommon(user->onlineTill, now)) {
return *common; return *common;
} }
const auto onlineFull = ParseDateTime(user->onlineTill); const auto onlineFull = base::unixtime::parse(user->onlineTill);
const auto nowFull = ParseDateTime(now); const auto nowFull = base::unixtime::parse(now);
if (onlineFull.date() == nowFull.date()) { if (onlineFull.date() == nowFull.date()) {
const auto onlineTime = onlineFull.time().toString(cTimeFormat()); const auto onlineTime = onlineFull.time().toString(cTimeFormat());
return tr::lng_status_lastseen_today(tr::now, lt_time, onlineTime); return tr::lng_status_lastseen_today(tr::now, lt_time, onlineTime);
@ -368,7 +369,7 @@ bool OnlineTextActive(not_null<UserData*> user, TimeId now) {
bool IsPeerAnOnlineUser(not_null<PeerData*> peer) { bool IsPeerAnOnlineUser(not_null<PeerData*> peer) {
if (const auto user = peer->asUser()) { if (const auto user = peer->asUser()) {
return OnlineTextActive(user, unixtime()); return OnlineTextActive(user, base::unixtime::now());
} }
return false; return false;
} }

View File

@ -44,6 +44,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_web_page.h" #include "data/data_web_page.h"
#include "data/data_game.h" #include "data/data_game.h"
#include "data/data_poll.h" #include "data/data_poll.h"
#include "base/unixtime.h"
#include "styles/style_boxes.h" // st::backgroundSize #include "styles/style_boxes.h" // st::backgroundSize
namespace Data { namespace Data {
@ -915,7 +916,7 @@ void Session::suggestStartExport() {
return; return;
} }
const auto now = unixtime(); const auto now = base::unixtime::now();
const auto left = (_exportAvailableAt <= now) const auto left = (_exportAvailableAt <= now)
? 0 ? 0
: (_exportAvailableAt - now); : (_exportAvailableAt - now);
@ -2243,7 +2244,7 @@ PhotoData *Session::photoFromWeb(
rand_value<PhotoId>(), rand_value<PhotoId>(),
uint64(0), uint64(0),
QByteArray(), QByteArray(),
unixtime(), base::unixtime::now(),
0, 0,
false, false,
thumbnailInline, thumbnailInline,
@ -2476,7 +2477,7 @@ DocumentData *Session::documentFromWeb(
rand_value<DocumentId>(), rand_value<DocumentId>(),
uint64(0), uint64(0),
QByteArray(), QByteArray(),
unixtime(), base::unixtime::now(),
data.vattributes().v, data.vattributes().v,
data.vmime_type().v, data.vmime_type().v,
ImagePtr(), ImagePtr(),
@ -2497,7 +2498,7 @@ DocumentData *Session::documentFromWeb(
rand_value<DocumentId>(), rand_value<DocumentId>(),
uint64(0), uint64(0),
QByteArray(), QByteArray(),
unixtime(), base::unixtime::now(),
data.vattributes().v, data.vattributes().v,
data.vmime_type().v, data.vmime_type().v,
ImagePtr(), ImagePtr(),
@ -2624,7 +2625,7 @@ not_null<WebPageData*> Session::processWebpage(const MTPDwebPagePending &data) {
QString(), QString(),
data.vdate().v data.vdate().v
? data.vdate().v ? data.vdate().v
: (unixtime() + kDefaultPendingTimeout)); : (base::unixtime::now() + kDefaultPendingTimeout));
return result; return result;
} }
@ -3455,7 +3456,7 @@ bool Session::notifyIsMuted(
not_null<const PeerData*> peer, not_null<const PeerData*> peer,
crl::time *changesIn) const { crl::time *changesIn) const {
const auto resultFromUntil = [&](TimeId until) { const auto resultFromUntil = [&](TimeId until) {
const auto now = unixtime(); const auto now = base::unixtime::now();
const auto result = (until > now) ? (until - now) : 0; const auto result = (until > now) ? (until - now) : 0;
if (changesIn) { if (changesIn) {
*changesIn = (result > 0) *changesIn = (result > 0)
@ -3532,7 +3533,7 @@ rpl::producer<> Session::defaultNotifyUpdates(
void Session::serviceNotification( void Session::serviceNotification(
const TextWithEntities &message, const TextWithEntities &message,
const MTPMessageMedia &media) { const MTPMessageMedia &media) {
const auto date = unixtime(); const auto date = base::unixtime::now();
if (!peerLoaded(PeerData::kServiceNotificationsId)) { if (!peerLoaded(PeerData::kServiceNotificationsId)) {
processUser(MTP_user( processUser(MTP_user(
MTP_flags( MTP_flags(

View File

@ -25,6 +25,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_chat.h" #include "data/data_chat.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "data/data_peer_values.h" #include "data/data_peer_values.h"
#include "base/unixtime.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "mainwidget.h" #include "mainwidget.h"
@ -2889,7 +2890,7 @@ void InnerWidget::userOnlineUpdated(const Notify::PeerUpdate &update) {
const auto visible = (top < _visibleBottom) const auto visible = (top < _visibleBottom)
&& (top + st::dialogsRowHeight > _visibleTop); && (top + st::dialogsRowHeight > _visibleTop);
row->setOnline( row->setOnline(
Data::OnlineTextActive(user, unixtime()), Data::OnlineTextActive(user, base::unixtime::now()),
visible ? Fn<void()>(crl::guard(this, repaint)) : nullptr); visible ? Fn<void()>(crl::guard(this, repaint)) : nullptr);
} }
} }

View File

@ -22,6 +22,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "history/history_item_components.h" #include "history/history_item_components.h"
#include "history/history_item.h" #include "history/history_item.h"
#include "history/history.h" #include "history/history.h"
#include "base/unixtime.h"
#include "data/data_channel.h" #include "data/data_channel.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "data/data_folder.h" #include "data/data_folder.h"
@ -639,11 +640,13 @@ void RowPainter::paint(
if (cloudDraft) { if (cloudDraft) {
return (item->date() > cloudDraft->date) return (item->date() > cloudDraft->date)
? ItemDateTime(item) ? ItemDateTime(item)
: ParseDateTime(cloudDraft->date); : base::unixtime::parse(cloudDraft->date);
} }
return ItemDateTime(item); return ItemDateTime(item);
} }
return cloudDraft ? ParseDateTime(cloudDraft->date) : QDateTime(); return cloudDraft
? base::unixtime::parse(cloudDraft->date)
: QDateTime();
}(); }();
const auto displayMentionBadge = history const auto displayMentionBadge = history
? history->hasUnreadMentions() ? history->hasUnreadMentions()

View File

@ -19,6 +19,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "platform/platform_info.h" #include "platform/platform_info.h"
#include "auth_session.h" #include "auth_session.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "base/unixtime.h"
#include "styles/style_export.h" #include "styles/style_export.h"
#include "styles/style_boxes.h" #include "styles/style_boxes.h"
@ -208,7 +209,7 @@ void PanelController::showError(const ApiErrorState &error) {
lt_date, lt_date,
langDateTimeFull(when))); langDateTimeFull(when)));
_settings->availableAt = unixtime() + seconds; _settings->availableAt = base::unixtime::now() + seconds;
_saveSettingsTimer.callOnce(kSaveSettingsTimeout); _saveSettingsTimer.callOnce(kSaveSettingsTimeout);
Auth().data().suggestStartExport(_settings->availableAt); Auth().data().suggestStartExport(_settings->availableAt);

View File

@ -23,6 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "platform/platform_specific.h" #include "platform/platform_specific.h"
#include "core/file_utilities.h" #include "core/file_utilities.h"
#include "boxes/calendar_box.h" #include "boxes/calendar_box.h"
#include "base/unixtime.h"
#include "auth_session.h" #include "auth_session.h"
#include "styles/style_widgets.h" #include "styles/style_widgets.h"
#include "styles/style_export.h" #include "styles/style_export.h"
@ -284,7 +285,8 @@ void SettingsWidget::addLimitsLabel(
}) | rpl::distinct_until_changed( }) | rpl::distinct_until_changed(
) | rpl::map([](TimeId from) { ) | rpl::map([](TimeId from) {
return (from return (from
? rpl::single(langDayOfMonthFull(ParseDateTime(from).date())) ? rpl::single(langDayOfMonthFull(
base::unixtime::parse(from).date()))
: tr::lng_export_beginning() : tr::lng_export_beginning()
) | Ui::Text::ToLink(qsl("internal:edit_from")); ) | Ui::Text::ToLink(qsl("internal:edit_from"));
}) | rpl::flatten_latest(); }) | rpl::flatten_latest();
@ -294,7 +296,8 @@ void SettingsWidget::addLimitsLabel(
}) | rpl::distinct_until_changed( }) | rpl::distinct_until_changed(
) | rpl::map([](TimeId till) { ) | rpl::map([](TimeId till) {
return (till return (till
? rpl::single(langDayOfMonthFull(ParseDateTime(till).date())) ? rpl::single(langDayOfMonthFull(
base::unixtime::parse(till).date()))
: tr::lng_export_end() : tr::lng_export_end()
) | Ui::Text::ToLink(qsl("internal:edit_till")); ) | Ui::Text::ToLink(qsl("internal:edit_till"));
}) | rpl::flatten_latest(); }) | rpl::flatten_latest();
@ -360,20 +363,20 @@ void SettingsWidget::editDateLimit(
Expects(_showBoxCallback != nullptr); Expects(_showBoxCallback != nullptr);
const auto highlighted = current const auto highlighted = current
? ParseDateTime(current).date() ? base::unixtime::parse(current).date()
: max : max
? ParseDateTime(max).date() ? base::unixtime::parse(max).date()
: min : min
? ParseDateTime(min).date() ? base::unixtime::parse(min).date()
: QDate::currentDate(); : QDate::currentDate();
const auto month = highlighted; const auto month = highlighted;
const auto shared = std::make_shared<QPointer<CalendarBox>>(); const auto shared = std::make_shared<QPointer<CalendarBox>>();
const auto finalize = [=](not_null<CalendarBox*> box) { const auto finalize = [=](not_null<CalendarBox*> box) {
box->setMaxDate(max box->setMaxDate(max
? ParseDateTime(max).date() ? base::unixtime::parse(max).date()
: QDate::currentDate()); : QDate::currentDate());
box->setMinDate(min box->setMinDate(min
? ParseDateTime(min).date() ? base::unixtime::parse(min).date()
: QDate(2013, 8, 1)); // Telegram was launched in August 2013 :) : QDate(2013, 8, 1)); // Telegram was launched in August 2013 :)
box->addLeftButton(std::move(resetLabel), crl::guard(this, [=] { box->addLeftButton(std::move(resetLabel), crl::guard(this, [=] {
done(0); done(0);
@ -383,7 +386,7 @@ void SettingsWidget::editDateLimit(
})); }));
}; };
const auto callback = crl::guard(this, [=](const QDate &date) { 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()) { if (const auto weak = shared->data()) {
weak->closeBox(); weak->closeBox();
} }

View File

@ -13,6 +13,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_peer_values.h" #include "data/data_peer_values.h"
#include "data/data_channel.h" #include "data/data_channel.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "base/unixtime.h"
#include "styles/style_boxes.h" #include "styles/style_boxes.h"
namespace AdminLog { namespace AdminLog {
@ -72,7 +73,7 @@ UserCheckbox::UserCheckbox(QWidget *parent, not_null<UserData*> user, bool check
if (isDisabled()) return; if (isDisabled()) return;
setChecked(!this->checked()); setChecked(!this->checked());
}); });
auto now = unixtime(); auto now = base::unixtime::now();
_statusText = Data::OnlineText(_user, now); _statusText = Data::OnlineText(_user, now);
_statusOnline = Data::OnlineTextActive(_user, now); _statusOnline = Data::OnlineTextActive(_user, now);
auto checkSize = _check->getSize(); auto checkSize = _check->getSize();

View File

@ -19,6 +19,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "ui/text/text_utilities.h" #include "ui/text/text_utilities.h"
#include "boxes/sticker_set_box.h" #include "boxes/sticker_set_box.h"
#include "base/unixtime.h"
#include "core/application.h" #include "core/application.h"
#include "mainwindow.h" // App::wnd()->sessionController #include "mainwindow.h" // App::wnd()->sessionController
#include "auth_session.h" #include "auth_session.h"
@ -218,7 +219,7 @@ TextWithEntities GenerateBannedChangeText(
: tr::lng_admin_log_restricted_until( : tr::lng_admin_log_restricted_until(
tr::now, tr::now,
lt_date, lt_date,
langDateTime(ParseDateTime(newUntil))); langDateTime(base::unixtime::parse(newUntil)));
auto result = tr::lng_admin_log_restricted( auto result = tr::lng_admin_log_restricted(
tr::now, tr::now,
lt_user, lt_user,

View File

@ -39,6 +39,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/image/image.h" #include "ui/image/image.h"
#include "ui/text_options.h" #include "ui/text_options.h"
#include "core/crash_reports.h" #include "core/crash_reports.h"
#include "base/unixtime.h"
#include "styles/style_dialogs.h" #include "styles/style_dialogs.h"
#include <memory> #include <memory>
@ -256,7 +257,7 @@ Data::Draft *History::createCloudDraft(const Data::Draft *fromDraft) {
existing->cursor = fromDraft->cursor; existing->cursor = fromDraft->cursor;
existing->previewCancelled = fromDraft->previewCancelled; existing->previewCancelled = fromDraft->previewCancelled;
} }
existing->date = unixtime(); existing->date = base::unixtime::now();
} }
cloudDraftTextCache.clear(); cloudDraftTextCache.clear();
@ -285,7 +286,7 @@ void History::clearSentDraftText(const QString &text) {
if (_lastSentDraftText && *_lastSentDraftText == text) { if (_lastSentDraftText && *_lastSentDraftText == text) {
_lastSentDraftText = std::nullopt; _lastSentDraftText = std::nullopt;
} }
accumulate_max(_lastSentDraftTime, unixtime()); accumulate_max(_lastSentDraftTime, base::unixtime::now());
} }
void History::setEditDraft(std::unique_ptr<Data::Draft> &&draft) { void History::setEditDraft(std::unique_ptr<Data::Draft> &&draft) {

View File

@ -34,6 +34,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "chat_helpers/message_field.h" #include "chat_helpers/message_field.h"
#include "chat_helpers/stickers.h" #include "chat_helpers/stickers.h"
#include "history/history_widget.h" #include "history/history_widget.h"
#include "base/unixtime.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "layout.h" #include "layout.h"
@ -1508,7 +1509,7 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
_widget->replyToMessage(itemId); _widget->replyToMessage(itemId);
}); });
} }
if (item->allowsEdit(unixtime())) { if (item->allowsEdit(base::unixtime::now())) {
_menu->addAction(tr::lng_context_edit_msg(tr::now), [=] { _menu->addAction(tr::lng_context_edit_msg(tr::now), [=] {
_widget->editMessage(itemId); _widget->editMessage(itemId);
}); });
@ -3109,7 +3110,7 @@ QString HistoryInner::tooltipText() const {
dateText += '\n' + tr::lng_edited_date( dateText += '\n' + tr::lng_edited_date(
tr::now, tr::now,
lt_date, lt_date,
ParseDateTime(editedDate).toString( base::unixtime::parse(editedDate).toString(
QLocale::system().dateTimeFormat( QLocale::system().dateTimeFormat(
QLocale::LongFormat))); QLocale::LongFormat)));
} }
@ -3117,7 +3118,7 @@ QString HistoryInner::tooltipText() const {
dateText += '\n' + tr::lng_forwarded_date( dateText += '\n' + tr::lng_forwarded_date(
tr::now, tr::now,
lt_date, lt_date,
ParseDateTime(forwarded->originalDate).toString( base::unixtime::parse(forwarded->originalDate).toString(
QLocale::system().dateTimeFormat( QLocale::system().dateTimeFormat(
QLocale::LongFormat))); QLocale::LongFormat)));
if (const auto media = view->media()) { if (const auto media = view->media()) {

View File

@ -31,6 +31,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mainwindow.h" #include "mainwindow.h"
#include "window/window_session_controller.h" #include "window/window_session_controller.h"
#include "core/crash_reports.h" #include "core/crash_reports.h"
#include "base/unixtime.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "data/data_messages.h" #include "data/data_messages.h"
#include "data/data_media_types.h" #include "data/data_media_types.h"
@ -271,7 +272,7 @@ void HistoryItem::finishEditionToEmpty() {
bool HistoryItem::hasUnreadMediaFlag() const { bool HistoryItem::hasUnreadMediaFlag() const {
if (_history->peer->isChannel()) { if (_history->peer->isChannel()) {
const auto passed = unixtime() - date(); const auto passed = base::unixtime::now() - date();
if (passed >= Global::ChannelsReadMediaPeriod()) { if (passed >= Global::ChannelsReadMediaPeriod()) {
return false; return false;
} }
@ -781,7 +782,7 @@ void HistoryItem::drawInDialog(
HistoryItem::~HistoryItem() = default; HistoryItem::~HistoryItem() = default;
QDateTime ItemDateTime(not_null<const HistoryItem*> item) { QDateTime ItemDateTime(not_null<const HistoryItem*> item) {
return ParseDateTime(item->date()); return base::unixtime::parse(item->date());
} }
ClickHandlerPtr goToMessageClickHandler( ClickHandlerPtr goToMessageClickHandler(

View File

@ -25,6 +25,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/image/image.h" #include "ui/image/image.h"
#include "ui/special_buttons.h" #include "ui/special_buttons.h"
#include "inline_bots/inline_bot_result.h" #include "inline_bots/inline_bot_result.h"
#include "base/unixtime.h"
#include "data/data_drafts.h" #include "data/data_drafts.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "data/data_web_page.h" #include "data/data_web_page.h"
@ -4305,7 +4306,7 @@ void HistoryWidget::sendFileConfirmed(
MTPMessageFwdHeader(), MTPMessageFwdHeader(),
MTPint(), MTPint(),
MTP_int(file->to.replyTo), MTP_int(file->to.replyTo),
MTP_int(unixtime()), MTP_int(base::unixtime::now()),
MTP_string(caption.text), MTP_string(caption.text),
photo, photo,
MTPReplyMarkup(), MTPReplyMarkup(),
@ -4336,7 +4337,7 @@ void HistoryWidget::sendFileConfirmed(
MTPMessageFwdHeader(), MTPMessageFwdHeader(),
MTPint(), MTPint(),
MTP_int(file->to.replyTo), MTP_int(file->to.replyTo),
MTP_int(unixtime()), MTP_int(base::unixtime::now()),
MTP_string(caption.text), MTP_string(caption.text),
document, document,
MTPReplyMarkup(), MTPReplyMarkup(),
@ -4370,7 +4371,7 @@ void HistoryWidget::sendFileConfirmed(
MTPMessageFwdHeader(), MTPMessageFwdHeader(),
MTPint(), MTPint(),
MTP_int(file->to.replyTo), MTP_int(file->to.replyTo),
MTP_int(unixtime()), MTP_int(base::unixtime::now()),
MTP_string(caption.text), MTP_string(caption.text),
document, document,
MTPReplyMarkup(), MTPReplyMarkup(),
@ -5154,7 +5155,7 @@ void HistoryWidget::keyPressEvent(QKeyEvent *e) {
? _history->lastSentMessage() ? _history->lastSentMessage()
: nullptr; : nullptr;
if (item if (item
&& item->allowsEdit(unixtime()) && item->allowsEdit(base::unixtime::now())
&& _field->empty() && _field->empty()
&& !_editMsgId && !_editMsgId
&& !_replyToId) { && !_replyToId) {
@ -5503,7 +5504,7 @@ bool HistoryWidget::sendExistingPhoto(
flags, flags,
0, 0,
options.replyTo, options.replyTo,
unixtime(), base::unixtime::now(),
messageFromId, messageFromId,
messagePostAuthor, messagePostAuthor,
photo, photo,
@ -5928,7 +5929,7 @@ void HistoryWidget::gotPreview(QString links, const MTPMessageMedia &result, mtp
const auto &data = result.c_messageMediaWebPage().vwebpage(); const auto &data = result.c_messageMediaWebPage().vwebpage();
const auto page = session().data().processWebpage(data); const auto page = session().data().processWebpage(data);
_previewCache.insert(links, page->id); _previewCache.insert(links, page->id);
if (page->pendingTill > 0 && page->pendingTill <= unixtime()) { if (page->pendingTill > 0 && page->pendingTill <= base::unixtime::now()) {
page->pendingTill = -1; page->pendingTill = -1;
} }
if (links == _previewLinks && !_previewCancelled) { if (links == _previewLinks && !_previewCancelled) {
@ -5967,7 +5968,7 @@ void HistoryWidget::updatePreview() {
TextUtilities::Clean(linkText), TextUtilities::Clean(linkText),
Ui::DialogTextOptions()); 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)); _previewTimer.callOnce(std::max(timeout, 0) * crl::time(1000));
} else { } else {
QString title, desc; QString title, desc;

View File

@ -34,6 +34,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_channel.h" #include "data/data_channel.h"
#include "data/data_chat.h" #include "data/data_chat.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "base/unixtime.h"
#include "support/support_helper.h" #include "support/support_helper.h"
#include "observer_peer.h" #include "observer_peer.h"
#include "apiwrap.h" #include "apiwrap.h"
@ -775,7 +776,7 @@ void TopBarWidget::updateOnlineDisplay() {
if (!_activeChat.peer()) return; if (!_activeChat.peer()) return;
QString text; QString text;
const auto now = unixtime(); const auto now = base::unixtime::now();
bool titlePeerTextOnline = false; bool titlePeerTextOnline = false;
if (const auto user = _activeChat.peer()->asUser()) { if (const auto user = _activeChat.peer()->asUser()) {
if (Auth().supportMode() if (Auth().supportMode()
@ -861,7 +862,7 @@ void TopBarWidget::updateOnlineDisplay() {
void TopBarWidget::updateOnlineDisplayTimer() { void TopBarWidget::updateOnlineDisplayTimer() {
if (!_activeChat.peer()) return; if (!_activeChat.peer()) return;
const auto now = unixtime(); const auto now = base::unixtime::now();
auto minTimeout = crl::time(86400); auto minTimeout = crl::time(86400);
const auto handleUser = [&](not_null<UserData*> user) { const auto handleUser = [&](not_null<UserData*> user) {
auto hisTimeout = Data::OnlineChangeTimeout(user, now); auto hisTimeout = Data::OnlineChangeTimeout(user, now);

View File

@ -23,6 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/text/text_utilities.h" // Ui::Text::ToUpper #include "ui/text/text_utilities.h" // Ui::Text::ToUpper
#include "ui/special_buttons.h" #include "ui/special_buttons.h"
#include "ui/unread_badge.h" #include "ui/unread_badge.h"
#include "base/unixtime.h"
#include "window/window_session_controller.h" #include "window/window_session_controller.h"
#include "observer_peer.h" #include "observer_peer.h"
#include "core/application.h" #include "core/application.h"
@ -394,7 +395,7 @@ void Cover::refreshStatusText() {
return false; return false;
}(); }();
auto statusText = [&] { auto statusText = [&] {
auto currentTime = unixtime(); auto currentTime = base::unixtime::now();
if (auto user = _peer->asUser()) { if (auto user = _peer->asUser()) {
const auto result = Data::OnlineTextFull(user, currentTime); const auto result = Data::OnlineTextFull(user, currentTime);
const auto showOnline = Data::OnlineTextActive(user, currentTime); const auto showOnline = Data::OnlineTextActive(user, currentTime);

View File

@ -83,6 +83,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/update_checker.h" #include "core/update_checker.h"
#include "core/shortcuts.h" #include "core/shortcuts.h"
#include "core/application.h" #include "core/application.h"
#include "base/unixtime.h"
#include "calls/calls_instance.h" #include "calls/calls_instance.h"
#include "calls/calls_top_bar.h" #include "calls/calls_top_bar.h"
#include "export/export_settings.h" #include "export/export_settings.h"
@ -3417,7 +3418,7 @@ void MainWidget::incrementSticker(DocumentData *sticker) {
} }
if (index) { if (index) {
if (it->dates.size() == it->stickers.size()) { 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); it->stickers.push_front(sticker);
if (const auto emojiList = Stickers::GetEmojiListFromSet(sticker)) { if (const auto emojiList = Stickers::GetEmojiListFromSet(sticker)) {
@ -3579,7 +3580,7 @@ void MainWidget::updateOnline(bool gotOtherOffline) {
} }
const auto self = session().user(); 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( Notify::peerUpdatedDelayed(
self, self,
Notify::PeerUpdate::Flag::UserOnlineChanged); Notify::PeerUpdate::Flag::UserOnlineChanged);
@ -4008,7 +4009,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
history->outboxRead(d.vmax_id().v); history->outboxRead(d.vmax_id().v);
if (!requestingDifference()) { if (!requestingDifference()) {
if (const auto user = history->peer->asUser()) { if (const auto user = history->peer->asUser()) {
user->madeAction(unixtime()); user->madeAction(base::unixtime::now());
} }
} }
if (_history->peer() && _history->peer()->id == peer) { 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 history = session().data().historyLoaded(userId);
const auto user = session().data().userLoaded(d.vuser_id().v); const auto user = session().data().userLoaded(d.vuser_id().v);
if (history && user) { 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); session().data().registerSendAction(history, user, d.vaction(), when);
} }
} break; } break;
@ -4136,7 +4137,7 @@ void MainWidget::feedUpdate(const MTPUpdate &update) {
? nullptr ? nullptr
: session().data().userLoaded(d.vuser_id().v); : session().data().userLoaded(d.vuser_id().v);
if (history && user) { 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); session().data().registerSendAction(history, user, d.vaction(), when);
} }
} break; } break;

View File

@ -38,6 +38,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "window/window_peer_menu.h" #include "window/window_peer_menu.h"
#include "window/window_controller.h" #include "window/window_controller.h"
#include "main/main_account.h" // Account::sessionValue. #include "main/main_account.h" // Account::sessionValue.
#include "base/unixtime.h"
#include "observer_peer.h" #include "observer_peer.h"
#include "auth_session.h" #include "auth_session.h"
#include "layout.h" #include "layout.h"
@ -554,9 +555,9 @@ void OverlayWidget::updateControls() {
if (const auto item = Auth().data().message(_msgid)) { if (const auto item = Auth().data().message(_msgid)) {
return ItemDateTime(item); return ItemDateTime(item);
} else if (_photo) { } else if (_photo) {
return ParseDateTime(_photo->date); return base::unixtime::parse(_photo->date);
} else if (_doc) { } else if (_doc) {
return ParseDateTime(_doc->date); return base::unixtime::parse(_doc->date);
} }
return dNow; return dNow;
}(); }();

View File

@ -24,13 +24,11 @@ ConfigLoader::ConfigLoader(
not_null<Instance*> instance, not_null<Instance*> instance,
const QString &phone, const QString &phone,
RPCDoneHandlerPtr onDone, RPCDoneHandlerPtr onDone,
RPCFailHandlerPtr onFail, RPCFailHandlerPtr onFail)
Fn<void(TimeId)> updateHttpUnixtime)
: _instance(instance) : _instance(instance)
, _phone(phone) , _phone(phone)
, _doneHandler(onDone) , _doneHandler(onDone)
, _failHandler(onFail) , _failHandler(onFail) {
, _updateHttpUnixtime(updateHttpUnixtime) {
_enumDCTimer.setCallback([this] { enumerate(); }); _enumDCTimer.setCallback([this] { enumerate(); });
_specialEnumTimer.setCallback([this] { sendSpecialRequest(); }); _specialEnumTimer.setCallback([this] { sendSpecialRequest(); });
} }
@ -131,7 +129,7 @@ void ConfigLoader::createSpecialLoader() {
int port, int port,
bytes::const_span secret) { bytes::const_span secret) {
addSpecialEndpoint(dcId, ip, port, secret); addSpecialEndpoint(dcId, ip, port, secret);
}, _updateHttpUnixtime, _phone); }, _phone);
} }
void ConfigLoader::addSpecialEndpoint( void ConfigLoader::addSpecialEndpoint(

View File

@ -25,8 +25,7 @@ public:
not_null<Instance*> instance, not_null<Instance*> instance,
const QString &phone, const QString &phone,
RPCDoneHandlerPtr onDone, RPCDoneHandlerPtr onDone,
RPCFailHandlerPtr onFail, RPCFailHandlerPtr onFail);
Fn<void(TimeId)> updateHttpUnixtime);
~ConfigLoader(); ~ConfigLoader();
void load(); void load();
@ -70,7 +69,6 @@ private:
RPCDoneHandlerPtr _doneHandler; RPCDoneHandlerPtr _doneHandler;
RPCFailHandlerPtr _failHandler; RPCFailHandlerPtr _failHandler;
Fn<void(TimeId)> _updateHttpUnixtime;
}; };

View File

@ -18,6 +18,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "base/openssl_help.h" #include "base/openssl_help.h"
#include "base/qthelp_url.h" #include "base/qthelp_url.h"
#include "base/unixtime.h"
extern "C" { extern "C" {
#include <openssl/bn.h> #include <openssl/bn.h>
@ -380,7 +381,9 @@ void ConnectionPrivate::appendTestConnection(
onDisconnected(weak); onDisconnected(weak);
}); });
connect(weak, &AbstractConnection::syncTimeRequest, [=] { connect(weak, &AbstractConnection::syncTimeRequest, [=] {
_instance->syncHttpUnixtime(); InvokeQueued(_instance, [instance = _instance] {
instance->syncHttpUnixtime();
});
}); });
InvokeQueued(_testConnections.back().data, [=] { InvokeQueued(_testConnections.back().data, [=] {
@ -526,7 +529,7 @@ void ConnectionPrivate::resetSession() { // recreate all msg_id and msg_seqno
auto &toSend = sessionData->toSendMap(); auto &toSend = sessionData->toSendMap();
auto &wereAcked = sessionData->wereAckedMap(); auto &wereAcked = sessionData->wereAckedMap();
auto newId = msgid(); auto newId = base::unixtime::mtproto_msg_id();
auto setSeqNumbers = RequestMap(); auto setSeqNumbers = RequestMap();
auto replaces = QMap<mtpMsgId, mtpMsgId>(); auto replaces = QMap<mtpMsgId, mtpMsgId>();
for (auto i = haveSent.cbegin(), e = haveSent.cend(); i != e; ++i) { 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()) { if (toResend.constFind(newId) == toResend.cend() && wereAcked.constFind(newId) == wereAcked.cend() && haveSent.constFind(newId) == haveSent.cend()) {
break; break;
} }
mtpMsgId m = msgid(); const auto m = base::unixtime::mtproto_msg_id();
if (m <= newId) break; // wtf if (m <= newId) break; // wtf
newId = m; 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()) { if (toResend.constFind(newId) == toResend.cend() && wereAcked.constFind(newId) == wereAcked.cend() && haveSent.constFind(newId) == haveSent.cend()) {
break; break;
} }
mtpMsgId m = msgid(); const auto m = base::unixtime::mtproto_msg_id();
if (m <= newId) break; // wtf if (m <= newId) break; // wtf
newId = m; 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()) { if (toResend.constFind(newId) == toResend.cend() && wereAcked.constFind(newId) == wereAcked.cend() && haveSent.constFind(newId) == haveSent.cend()) {
break; break;
} }
const auto m = msgid(); const auto m = base::unixtime::mtproto_msg_id();
if (m <= newId) break; // wtf if (m <= newId) break; // wtf
newId = m; 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 ConnectionPrivate::placeToContainer(SecureRequest &toSendRequest, mtpMsgId &bigMsgId, mtpMsgId *&haveSentArr, SecureRequest &req) {
mtpMsgId msgId = prepareToSend(req, bigMsgId); auto msgId = prepareToSend(req, bigMsgId);
if (msgId > bigMsgId) msgId = replaceMsgId(req, bigMsgId); if (msgId > bigMsgId) {
if (msgId >= bigMsgId) bigMsgId = msgid(); msgId = replaceMsgId(req, bigMsgId);
}
if (msgId >= bigMsgId) {
bigMsgId = base::unixtime::mtproto_msg_id();
}
*(haveSentArr++) = msgId; *(haveSentArr++) = msgId;
uint32 from = toSendRequest->size(), len = req.messageSize(); uint32 from = toSendRequest->size(), len = req.messageSize();
@ -890,7 +897,9 @@ void ConnectionPrivate::tryToSend() {
locker1.unlock(); locker1.unlock();
} }
mtpMsgId msgId = prepareToSend(toSendRequest, msgid()); const auto msgId = prepareToSend(
toSendRequest,
base::unixtime::mtproto_msg_id());
if (pingRequest) { if (pingRequest) {
_pingMsgId = msgId; _pingMsgId = msgId;
needAnyResponse = true; needAnyResponse = true;
@ -965,7 +974,8 @@ void ConnectionPrivate::tryToSend() {
toSendRequest->push_back(mtpc_msg_container); toSendRequest->push_back(mtpc_msg_container);
toSendRequest->push_back(toSendCount); 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() // the fact of this lock is used in replaceMsgId()
QWriteLocker locker2(sessionData->haveSentMutex()); QWriteLocker locker2(sessionData->haveSentMutex());
@ -990,8 +1000,12 @@ void ConnectionPrivate::tryToSend() {
for (auto i = toSend.begin(), e = toSend.end(); i != e; ++i) { for (auto i = toSend.begin(), e = toSend.end(); i != e; ++i) {
auto &req = i.value(); auto &req = i.value();
auto msgId = prepareToSend(req, bigMsgId); auto msgId = prepareToSend(req, bigMsgId);
if (msgId > bigMsgId) msgId = replaceMsgId(req, bigMsgId); if (msgId > bigMsgId) {
if (msgId >= bigMsgId) bigMsgId = msgid(); msgId = replaceMsgId(req, bigMsgId);
}
if (msgId >= bigMsgId) {
bigMsgId = base::unixtime::mtproto_msg_id();
}
*(haveSentArr++) = msgId; *(haveSentArr++) = msgId;
bool added = false; bool added = false;
if (req->requestId) { if (req->requestId) {
@ -1523,8 +1537,9 @@ void ConnectionPrivate::handleReceived() {
return restartOnError(); return restartOnError();
} }
int32 serverTime((int32)(msgId >> 32)), clientTime(unixtime()); const auto serverTime = int32(msgId >> 32);
bool isReply = ((msgId & 0x03) == 1); const auto clientTime = base::unixtime::now();
const auto isReply = ((msgId & 0x03) == 1);
if (!isReply && ((msgId & 0x03) != 3)) { if (!isReply && ((msgId & 0x03) != 3)) {
LOG(("MTP Error: bad msg_id %1 in message received").arg(msgId)); 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 (needResend) { // bad msg_id or bad container
if (serverSalt) sessionData->setSalt(serverSalt); 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)); 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 } else { // must create new session, because msg_id and msg_seqno are inconsistent
if (badTime) { if (badTime) {
if (serverSalt) sessionData->setSalt(serverSalt); if (serverSalt) sessionData->setSalt(serverSalt);
unixtimeSet(serverTime, true); base::unixtime::update(serverTime, true);
badTime = false; badTime = false;
} }
LOG(("Message Info: bad message notification received, msgId %1, error_code %2").arg(data.vbad_msg_id().v).arg(errorCode)); 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; uint64 serverSalt = data.vnew_server_salt().v;
sessionData->setSalt(serverSalt); sessionData->setSalt(serverSalt);
unixtimeSet(serverTime); base::unixtime::update(serverTime);
if (setState(ConnectedState, ConnectingState)) { // maybe only connected if (setState(ConnectedState, ConnectingState)) { // maybe only connected
if (restarted) { if (restarted) {
@ -1908,7 +1923,7 @@ ConnectionPrivate::HandleResult ConnectionPrivate::handleOneReceived(const mtpPr
} }
if (badTime) { if (badTime) {
if (serverSalt) sessionData->setSalt(serverSalt); // requestsFixTimeSalt with no lookup 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)); DEBUG_LOG(("Message Info: unixtime updated from mtpc_msgs_state_info, now %1").arg(serverTime));
@ -2243,7 +2258,7 @@ bool ConnectionPrivate::requestsFixTimeSalt(const QVector<MTPlong> &ids, int32 s
for (uint32 i = 0; i < idsCount; ++i) { 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 (wasSent(ids[i].v)) {// found such msg_id in recent acked requests or in recent sent requests
if (serverSalt) sessionData->setSalt(serverSalt); if (serverSalt) sessionData->setSalt(serverSalt);
unixtimeSet(serverTime, true); base::unixtime::update(serverTime, true);
return 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())); 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(); 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 // 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)) { if (!IsPrimeAndGood(bytes::make_span(dh_inner_data.vdh_prime().v), dh_inner_data.vg().v)) {
@ -3053,7 +3068,9 @@ void ConnectionPrivate::onReadyData() {
template <typename Request> template <typename Request>
void ConnectionPrivate::sendNotSecureRequest(const Request &request) { 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" DEBUG_LOG(("AuthKey Info: sending request, size: %1, time: %3"
).arg(packet.size() - 8 ).arg(packet.size() - 8

View File

@ -11,6 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/connection_http.h" #include "mtproto/connection_http.h"
#include "mtproto/connection_resolving.h" #include "mtproto/connection_resolving.h"
#include "mtproto/session.h" #include "mtproto/session.h"
#include "base/unixtime.h"
namespace MTP { namespace MTP {
namespace internal { namespace internal {
@ -111,8 +112,8 @@ gsl::span<const mtpPrime> AbstractConnection::parseNotSecureResponse(
if (answer[0] != 0 if (answer[0] != 0
|| answer[1] != 0 || answer[1] != 0
|| (((uint32)answer[2]) & 0x03) != 1 || (((uint32)answer[2]) & 0x03) != 1
//|| (unixtime() - answer[3] > 300) // We didn't sync time yet. //|| (base::unixtime::now() - answer[3] > 300) // We didn't sync time yet.
//|| (answer[3] - unixtime() > 60) //|| (answer[3] - base::unixtime::now() > 60)
|| false) { || false) {
LOG(("Not Secure Error: bad request answer start (%1 %2 %3)" LOG(("Not Secure Error: bad request answer start (%1 %2 %3)"
).arg(answer[0] ).arg(answer[0]
@ -135,7 +136,9 @@ gsl::span<const mtpPrime> AbstractConnection::parseNotSecureResponse(
} }
mtpBuffer AbstractConnection::preparePQFake(const MTPint128 &nonce) const { 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( MTPResPQ AbstractConnection::readPQFakeReply(

View File

@ -103,7 +103,9 @@ public:
} }
template <typename Request> template <typename Request>
mtpBuffer prepareNotSecurePacket(const Request &request) const; mtpBuffer prepareNotSecurePacket(
const Request &request,
mtpMsgId newId) const;
mtpBuffer prepareSecurePacket( mtpBuffer prepareSecurePacket(
uint64 keyId, uint64 keyId,
MTPint128 msgKey, MTPint128 msgKey,
@ -140,7 +142,9 @@ protected:
}; };
template <typename Request> template <typename Request>
mtpBuffer AbstractConnection::prepareNotSecurePacket(const Request &request) const { mtpBuffer AbstractConnection::prepareNotSecurePacket(
const Request &request,
mtpMsgId newId) const {
const auto intsSize = request.innerLength() >> 2; const auto intsSize = request.innerLength() >> 2;
const auto intsPadding = requiresExtendedPadding() const auto intsPadding = requiresExtendedPadding()
? uint32(rand_value<uchar>() & 0x3F) ? uint32(rand_value<uchar>() & 0x3F)
@ -161,7 +165,7 @@ mtpBuffer AbstractConnection::prepareNotSecurePacket(const Request &request) con
result.resize(kPrefixInts); result.resize(kPrefixInts);
const auto messageId = &result[kTcpPrefixInts + kAuthKeyIdInts]; const auto messageId = &result[kTcpPrefixInts + kAuthKeyIdInts];
*reinterpret_cast<mtpMsgId*>(messageId) = msgid(); *reinterpret_cast<mtpMsgId*>(messageId) = newId;
request.write(result); request.write(result);

View File

@ -558,8 +558,7 @@ void TcpConnection::connectToServer(
_socket = AbstractSocket::Create( _socket = AbstractSocket::Create(
thread(), thread(),
secret, secret,
ToNetworkProxy(_proxy), ToNetworkProxy(_proxy));
[=] { return _instance->httpUnixtime(); });
_protocolDcId = protocolDcId; _protocolDcId = protocolDcId;
_socket->connected( _socket->connected(

View File

@ -16,10 +16,9 @@ namespace internal {
std::unique_ptr<AbstractSocket> AbstractSocket::Create( std::unique_ptr<AbstractSocket> AbstractSocket::Create(
not_null<QThread*> thread, not_null<QThread*> thread,
const bytes::vector &secret, const bytes::vector &secret,
const QNetworkProxy &proxy, const QNetworkProxy &proxy) {
Fn<int32()> unixtime) {
if (secret.size() >= 21 && secret[0] == bytes::type(0xEE)) { if (secret.size() >= 21 && secret[0] == bytes::type(0xEE)) {
return std::make_unique<TlsSocket>(thread, secret, proxy, unixtime); return std::make_unique<TlsSocket>(thread, secret, proxy);
} else { } else {
return std::make_unique<TcpSocket>(thread, proxy); return std::make_unique<TcpSocket>(thread, proxy);
} }

View File

@ -18,8 +18,7 @@ public:
static std::unique_ptr<AbstractSocket> Create( static std::unique_ptr<AbstractSocket> Create(
not_null<QThread*> thread, not_null<QThread*> thread,
const bytes::vector &secret, const bytes::vector &secret,
const QNetworkProxy &proxy, const QNetworkProxy &proxy);
Fn<int32()> unixtime);
explicit AbstractSocket(not_null<QThread*> thread) { explicit AbstractSocket(not_null<QThread*> thread) {
moveToThread(thread); moveToThread(thread);

View File

@ -20,6 +20,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "core/application.h" #include "core/application.h"
#include "base/unixtime.h"
#include "lang/lang_instance.h" #include "lang/lang_instance.h"
#include "lang/lang_cloud_manager.h" #include "lang/lang_cloud_manager.h"
#include "base/timer.h" #include "base/timer.h"
@ -60,10 +61,7 @@ public:
void requestCDNConfig(); void requestCDNConfig();
void setUserPhone(const QString &phone); void setUserPhone(const QString &phone);
void badConfigurationError(); void badConfigurationError();
// Thread safe.
void syncHttpUnixtime(); void syncHttpUnixtime();
[[nodiscard]] int32 httpUnixtime() const;
void restart(); void restart();
void restart(ShiftedDcId shiftedDcId); void restart(ShiftedDcId shiftedDcId);
@ -168,7 +166,6 @@ private:
void clearCallbacks(const std::vector<RPCCallbackClear> &ids); void clearCallbacks(const std::vector<RPCCallbackClear> &ids);
void checkDelayedRequests(); void checkDelayedRequests();
[[nodiscard]] Fn<void(TimeId)> updateHttpUnixtime();
not_null<Instance*> _instance; not_null<Instance*> _instance;
not_null<DcOptions*> _dcOptions; not_null<DcOptions*> _dcOptions;
@ -194,8 +191,6 @@ private:
mtpRequestId _cdnConfigLoadRequestId = 0; mtpRequestId _cdnConfigLoadRequestId = 0;
crl::time _lastConfigLoadedTime = 0; crl::time _lastConfigLoadedTime = 0;
crl::time _configExpiresAt = 0; crl::time _configExpiresAt = 0;
std::atomic<bool> _httpUnixtimeValid = false;
std::atomic<TimeId> _httpUnixtimeShift = 0;
std::map<DcId, AuthKeyPtr> _keysForWrite; std::map<DcId, AuthKeyPtr> _keysForWrite;
mutable QReadWriteLock _keysForWriteLock; mutable QReadWriteLock _keysForWriteLock;
@ -250,8 +245,6 @@ void Instance::Private::start(Config &&config) {
if (isKeysDestroyer()) { if (isKeysDestroyer()) {
_instance->connect(_instance, SIGNAL(keyDestroyed(qint32)), _instance, SLOT(onKeyDestroyed(qint32)), Qt::QueuedConnection); _instance->connect(_instance, SIGNAL(keyDestroyed(qint32)), _instance, SLOT(onKeyDestroyed(qint32)), Qt::QueuedConnection);
} else if (isNormal()) {
unixtimeInit();
} }
for (auto &key : config.keys) { for (auto &key : config.keys) {
@ -413,8 +406,7 @@ void Instance::Private::requestConfig() {
_instance, _instance,
_userPhone, _userPhone,
rpcDone([=](const MTPConfig &result) { configLoadDone(result); }), rpcDone([=](const MTPConfig &result) { configLoadDone(result); }),
rpcFail([=](const RPCError &error) { return configLoadFail(error); }), rpcFail([=](const RPCError &error) { return configLoadFail(error); }));
updateHttpUnixtime());
_configLoader->load(); _configLoader->load();
} }
@ -433,33 +425,15 @@ void Instance::Private::badConfigurationError() {
} }
} }
int32 Instance::Private::httpUnixtime() const {
return unixtime() + _httpUnixtimeShift;
}
void Instance::Private::syncHttpUnixtime() { void Instance::Private::syncHttpUnixtime() {
if (_httpUnixtimeValid) { if (base::unixtime::http_valid() || _httpUnixtimeLoader) {
return; return;
} }
InvokeQueued(_instance, [=] { _httpUnixtimeLoader = std::make_unique<SpecialConfigRequest>([=] {
if (_httpUnixtimeValid || _httpUnixtimeLoader) {
return;
}
_httpUnixtimeLoader = std::make_unique<SpecialConfigRequest>(
updateHttpUnixtime());
});
}
Fn<void(TimeId)> Instance::Private::updateHttpUnixtime() {
return [=](TimeId httpUnixtime) {
_httpUnixtimeValid = true;
_httpUnixtimeShift = httpUnixtime - unixtime();
InvokeQueued(_instance, [=] { InvokeQueued(_instance, [=] {
if (_httpUnixtimeValid) { _httpUnixtimeLoader = nullptr;
_httpUnixtimeLoader = nullptr;
}
}); });
}; });
} }
void Instance::Private::requestConfigIfOld() { void Instance::Private::requestConfigIfOld() {
@ -842,7 +816,7 @@ void Instance::Private::configLoadDone(const MTPConfig &result) {
Local::writeSettings(); Local::writeSettings();
_configExpiresAt = crl::now() _configExpiresAt = crl::now()
+ (data.vexpires().v - unixtime()) * crl::time(1000); + (data.vexpires().v - base::unixtime::now()) * crl::time(1000);
requestConfigIfExpired(); requestConfigIfExpired();
emit _instance->configLoaded(); emit _instance->configLoaded();
@ -1615,10 +1589,6 @@ void Instance::badConfigurationError() {
_private->badConfigurationError(); _private->badConfigurationError();
} }
int32 Instance::httpUnixtime() const {
return _private->httpUnixtime();
}
void Instance::syncHttpUnixtime() { void Instance::syncHttpUnixtime() {
_private->syncHttpUnixtime(); _private->syncHttpUnixtime();
} }

View File

@ -180,8 +180,6 @@ public:
void setUserPhone(const QString &phone); void setUserPhone(const QString &phone);
void badConfigurationError(); void badConfigurationError();
// Thread safe.
[[nodiscard]] int32 httpUnixtime() const;
void syncHttpUnixtime(); void syncHttpUnixtime();
~Instance(); ~Instance();

View File

@ -11,6 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "base/openssl_help.h" #include "base/openssl_help.h"
#include "base/bytes.h" #include "base/bytes.h"
#include "base/invoke_queued.h" #include "base/invoke_queued.h"
#include "base/unixtime.h"
#include <QtCore/QtEndian> #include <QtCore/QtEndian>
@ -136,8 +137,7 @@ public:
ClientHelloGenerator( ClientHelloGenerator(
const MTPTlsClientHello &rules, const MTPTlsClientHello &rules,
bytes::const_span domain, bytes::const_span domain,
bytes::const_span key, bytes::const_span key);
Fn<int32()> unixtime);
[[nodiscard]] ClientHello result(); [[nodiscard]] ClientHello result();
private: private:
@ -156,7 +156,6 @@ private:
bytes::const_span _domain; bytes::const_span _domain;
bytes::const_span _key; bytes::const_span _key;
Fn<int32()> _unixtime;
bytes::vector _greases; bytes::vector _greases;
std::vector<int> _scopeStack; std::vector<int> _scopeStack;
QByteArray _result; QByteArray _result;
@ -169,11 +168,9 @@ private:
ClientHelloGenerator::ClientHelloGenerator( ClientHelloGenerator::ClientHelloGenerator(
const MTPTlsClientHello &rules, const MTPTlsClientHello &rules,
bytes::const_span domain, bytes::const_span domain,
bytes::const_span key, bytes::const_span key)
Fn<int32()> unixtime)
: _domain(domain) : _domain(domain)
, _key(key) , _key(key)
, _unixtime(unixtime)
, _greases(PrepareGreases()) { , _greases(PrepareGreases()) {
_result.reserve(kClientHelloLength); _result.reserve(kClientHelloLength);
writeBlocks(rules.match([&](const MTPDtlsClientHello &data) { writeBlocks(rules.match([&](const MTPDtlsClientHello &data) {
@ -304,7 +301,7 @@ void ClientHelloGenerator::writeTimestamp() {
sizeof(int32)); sizeof(int32));
auto already = int32(); auto already = int32();
bytes::copy(bytes::object_as_span(&already), storage); 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)); bytes::copy(storage, bytes::object_as_span(&already));
_digest = QByteArray(kHelloDigestLength, Qt::Uninitialized); _digest = QByteArray(kHelloDigestLength, Qt::Uninitialized);
@ -318,9 +315,8 @@ void ClientHelloGenerator::writeTimestamp() {
[[nodiscard]] ClientHello PrepareClientHello( [[nodiscard]] ClientHello PrepareClientHello(
const MTPTlsClientHello &rules, const MTPTlsClientHello &rules,
bytes::const_span domain, bytes::const_span domain,
bytes::const_span key, bytes::const_span key) {
Fn<int32()> unixtime) { return ClientHelloGenerator(rules, domain, key).result();
return ClientHelloGenerator(rules, domain, key, unixtime).result();
} }
[[nodiscard]] bool CheckPart(bytes::const_span data, QLatin1String check) { [[nodiscard]] bool CheckPart(bytes::const_span data, QLatin1String check) {
@ -343,13 +339,10 @@ void ClientHelloGenerator::writeTimestamp() {
TlsSocket::TlsSocket( TlsSocket::TlsSocket(
not_null<QThread*> thread, not_null<QThread*> thread,
const bytes::vector &secret, const bytes::vector &secret,
const QNetworkProxy &proxy, const QNetworkProxy &proxy)
Fn<int32()> unixtime)
: AbstractSocket(thread) : AbstractSocket(thread)
, _secret(secret) , _secret(secret) {
, _unixtime(unixtime) {
Expects(_secret.size() >= 21 && _secret[0] == bytes::type(0xEE)); Expects(_secret.size() >= 21 && _secret[0] == bytes::type(0xEE));
Expects(_unixtime != nullptr);
_socket.moveToThread(thread); _socket.moveToThread(thread);
_socket.setProxy(proxy); _socket.setProxy(proxy);
@ -397,8 +390,7 @@ void TlsSocket::plainConnected() {
const auto hello = PrepareClientHello( const auto hello = PrepareClientHello(
kClientHelloRules, kClientHelloRules,
domainFromSecret(), domainFromSecret(),
keyFromSecret(), keyFromSecret());
_unixtime);
if (hello.data.isEmpty()) { if (hello.data.isEmpty()) {
LOG(("TLS Error: Could not generate Client Hello!")); LOG(("TLS Error: Could not generate Client Hello!"));
_state = State::Error; _state = State::Error;

View File

@ -17,8 +17,7 @@ public:
TlsSocket( TlsSocket(
not_null<QThread*> thread, not_null<QThread*> thread,
const bytes::vector &secret, const bytes::vector &secret,
const QNetworkProxy &proxy, const QNetworkProxy &proxy);
Fn<int32()> unixtime);
void connectToHost(const QString &address, int port) override; void connectToHost(const QString &address, int port) override;
void timedOut() override; void timedOut() override;
@ -56,7 +55,6 @@ private:
const bytes::vector _secret; const bytes::vector _secret;
QTcpSocket _socket; QTcpSocket _socket;
Fn<int32()> _unixtime;
State _state = State::NotConnected; State _state = State::NotConnected;
QByteArray _incoming; QByteArray _incoming;
int _incomingGoodDataOffset = 0; int _incomingGoodDataOffset = 0;

View File

@ -10,6 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/connection.h" #include "mtproto/connection.h"
#include "mtproto/dcenter.h" #include "mtproto/dcenter.h"
#include "mtproto/auth_key.h" #include "mtproto/auth_key.h"
#include "base/unixtime.h"
#include "core/crash_reports.h" #include "core/crash_reports.h"
namespace MTP { namespace MTP {
@ -329,7 +330,8 @@ void Session::checkRequestsByTimer() {
stateRequestIds.push_back(i.key()); 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.reserve(haveSentCount);
removingIds.push_back(i.key()); removingIds.push_back(i.key());
} }

View File

@ -10,6 +10,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/rsa_public_key.h" #include "mtproto/rsa_public_key.h"
#include "mtproto/dc_options.h" #include "mtproto/dc_options.h"
#include "mtproto/auth_key.h" #include "mtproto/auth_key.h"
#include "base/unixtime.h"
#include "base/openssl_help.h" #include "base/openssl_help.h"
extern "C" { extern "C" {
@ -258,11 +259,13 @@ SpecialConfigRequest::SpecialConfigRequest(
const std::string &ip, const std::string &ip,
int port, int port,
bytes::const_span secret)> callback, bytes::const_span secret)> callback,
Fn<void(TimeId)> timeCallback, Fn<void()> timeDoneCallback,
const QString &phone) const QString &phone)
: _callback(std::move(callback)) : _callback(std::move(callback))
, _timeCallback(std::move(timeCallback)) , _timeDoneCallback(std::move(timeDoneCallback))
, _phone(phone) { , _phone(phone) {
Expects((_callback == nullptr) != (_timeDoneCallback == nullptr));
_manager.setProxy(QNetworkProxy::NoProxy); _manager.setProxy(QNetworkProxy::NoProxy);
_attempts = { _attempts = {
//{ Type::App, qsl("software-download.microsoft.com") }, //{ Type::App, qsl("software-download.microsoft.com") },
@ -275,8 +278,18 @@ SpecialConfigRequest::SpecialConfigRequest(
sendNextRequest(); sendNextRequest();
} }
SpecialConfigRequest::SpecialConfigRequest(Fn<void(TimeId)> timeCallback) SpecialConfigRequest::SpecialConfigRequest(
: SpecialConfigRequest(nullptr, std::move(timeCallback), QString()) { Fn<void(
DcId dcId,
const std::string &ip,
int port,
bytes::const_span secret)> callback,
const QString &phone)
: SpecialConfigRequest(std::move(callback), nullptr, phone) {
}
SpecialConfigRequest::SpecialConfigRequest(Fn<void()> timeDoneCallback)
: SpecialConfigRequest(nullptr, std::move(timeDoneCallback), QString()) {
} }
void SpecialConfigRequest::sendNextRequest() { void SpecialConfigRequest::sendNextRequest() {
@ -326,7 +339,7 @@ void SpecialConfigRequest::performRequest(const Attempt &attempt) {
void SpecialConfigRequest::handleHeaderUnixtime( void SpecialConfigRequest::handleHeaderUnixtime(
not_null<QNetworkReply*> reply) { not_null<QNetworkReply*> reply) {
if (!_timeCallback || reply->error() != QNetworkReply::NoError) { if (reply->error() != QNetworkReply::NoError) {
return; return;
} }
const auto date = QString::fromLatin1([&] { const auto date = QString::fromLatin1([&] {
@ -346,7 +359,10 @@ void SpecialConfigRequest::handleHeaderUnixtime(
LOG(("Config Error: Bad 'Date' header received: %1").arg(date)); LOG(("Config Error: Bad 'Date' header received: %1").arg(date));
return; return;
} }
_timeCallback(parsed.toTime_t()); base::unixtime::http_update(parsed.toTime_t());
if (_timeDoneCallback) {
_timeDoneCallback();
}
} }
void SpecialConfigRequest::requestFinished( void SpecialConfigRequest::requestFinished(
@ -460,9 +476,9 @@ void SpecialConfigRequest::handleResponse(const QByteArray &bytes) {
return; return;
} }
Assert(_simpleConfig.type() == mtpc_help_configSimple); Assert(_simpleConfig.type() == mtpc_help_configSimple);
auto &config = _simpleConfig.c_help_configSimple(); const auto &config = _simpleConfig.c_help_configSimple();
auto now = unixtime(); const auto now = base::unixtime::now();
if (now < config.vdate().v || now > config.vexpires().v) { 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)); 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; return;
} }

View File

@ -31,9 +31,8 @@ public:
const std::string &ip, const std::string &ip,
int port, int port,
bytes::const_span secret)> callback, bytes::const_span secret)> callback,
Fn<void(TimeId)> timeCallback,
const QString &phone); const QString &phone);
explicit SpecialConfigRequest(Fn<void(TimeId)> timeCallback); explicit SpecialConfigRequest(Fn<void()> timeDoneCallback);
private: private:
enum class Type { enum class Type {
@ -45,6 +44,15 @@ private:
QString domain; QString domain;
}; };
SpecialConfigRequest(
Fn<void(
DcId dcId,
const std::string &ip,
int port,
bytes::const_span secret)> callback,
Fn<void()> timeDoneCallback,
const QString &phone);
void sendNextRequest(); void sendNextRequest();
void performRequest(const Attempt &attempt); void performRequest(const Attempt &attempt);
void requestFinished(Type type, not_null<QNetworkReply*> reply); void requestFinished(Type type, not_null<QNetworkReply*> reply);
@ -58,7 +66,7 @@ private:
const std::string &ip, const std::string &ip,
int port, int port,
bytes::const_span secret)> _callback; bytes::const_span secret)> _callback;
Fn<void(TimeId)> _timeCallback; Fn<void()> _timeDoneCallback;
QString _phone; QString _phone;
MTPhelp_ConfigSimple _simpleConfig; MTPhelp_ConfigSimple _simpleConfig;

View File

@ -27,6 +27,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "history/history_item.h" #include "history/history_item.h"
#include "history/history_item_components.h" #include "history/history_item_components.h"
#include "history/view/history_view_cursor_state.h" #include "history/view/history_view_cursor_state.h"
#include "base/unixtime.h"
#include "ui/effects/round_checkbox.h" #include "ui/effects/round_checkbox.h"
#include "ui/image/image.h" #include "ui/image/image.h"
#include "ui/text_options.h" #include "ui/text_options.h"
@ -591,7 +592,7 @@ Voice::Voice(
const auto dateText = textcmdLink( const auto dateText = textcmdLink(
1, 1,
TextUtilities::EscapeForRichParsing( TextUtilities::EscapeForRichParsing(
langDateTime(ParseDateTime(_data->date)))); langDateTime(base::unixtime::parse(_data->date))));
TextParseOptions opts = { TextParseRichText, 0, 0, Qt::LayoutDirectionAuto }; TextParseOptions opts = { TextParseRichText, 0, 0, Qt::LayoutDirectionAuto };
_details.setText( _details.setText(
st::defaultTextStyle, st::defaultTextStyle,
@ -871,7 +872,7 @@ Document::Document(
, _msgl(goToMessageClickHandler(parent)) , _msgl(goToMessageClickHandler(parent))
, _namel(std::make_shared<DocumentOpenClickHandler>(_data, parent->fullId())) , _namel(std::make_shared<DocumentOpenClickHandler>(_data, parent->fullId()))
, _st(st) , _st(st)
, _date(langDateTime(ParseDateTime(_data->date))) , _date(langDateTime(base::unixtime::parse(_data->date)))
, _datew(st::normalFont->width(_date)) , _datew(st::normalFont->width(_date))
, _colorIndex(documentColorIndex(_data, _ext)) { , _colorIndex(documentColorIndex(_data, _ext)) {
_name.setMarkedText(st::defaultTextStyle, ComposeNameWithEntities(_data), _documentNameOptions); _name.setMarkedText(st::defaultTextStyle, ComposeNameWithEntities(_data), _documentNameOptions);

View File

@ -16,6 +16,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_hardcoded.h" #include "lang/lang_hardcoded.h"
#include "base/openssl_help.h" #include "base/openssl_help.h"
#include "base/qthelp_url.h" #include "base/qthelp_url.h"
#include "base/unixtime.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "data/data_user.h" #include "data/data_user.h"
#include "mainwindow.h" #include "mainwindow.h"
@ -1402,7 +1403,7 @@ void FormController::prepareFile(
file.fields.id = fileId; file.fields.id = fileId;
file.fields.dcId = MTP::maindc(); file.fields.dcId = MTP::maindc();
file.fields.secret = GenerateSecretBytes(); file.fields.secret = GenerateSecretBytes();
file.fields.date = unixtime(); file.fields.date = base::unixtime::now();
file.fields.image = ReadImage(bytes::make_span(content)); file.fields.image = ReadImage(bytes::make_span(content));
file.fields.downloadOffset = file.fields.size; file.fields.downloadOffset = file.fields.size;

View File

@ -14,6 +14,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "passport/passport_panel_edit_scans.h" #include "passport/passport_panel_edit_scans.h"
#include "passport/passport_panel.h" #include "passport/passport_panel.h"
#include "base/openssl_help.h" #include "base/openssl_help.h"
#include "base/unixtime.h"
#include "boxes/passcode_box.h" #include "boxes/passcode_box.h"
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "ui/toast/toast.h" #include "ui/toast/toast.h"
@ -48,7 +49,8 @@ ScanInfo CollectScanInfo(const EditFile &file) {
return tr::lng_passport_scan_uploaded( return tr::lng_passport_scan_uploaded(
tr::now, tr::now,
lt_date, lt_date,
langDateTimeFull(ParseDateTime(file.fields.date))); langDateTimeFull(
base::unixtime::parse(file.fields.date)));
} }
} else if (file.uploadData) { } else if (file.uploadData) {
if (file.uploadData->offset < 0) { if (file.uploadData->offset < 0) {
@ -61,7 +63,8 @@ ScanInfo CollectScanInfo(const EditFile &file) {
return tr::lng_passport_scan_uploaded( return tr::lng_passport_scan_uploaded(
tr::now, tr::now,
lt_date, lt_date,
langDateTimeFull(ParseDateTime(file.fields.date))); langDateTimeFull(
base::unixtime::parse(file.fields.date)));
} }
} else { } else {
return formatDownloadText(0, file.fields.size); return formatDownloadText(0, file.fields.size);

View File

@ -12,6 +12,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/confirm_box.h" #include "boxes/confirm_box.h"
#include "boxes/peers/edit_participant_box.h" #include "boxes/peers/edit_participant_box.h"
#include "boxes/peers/edit_participants_box.h" #include "boxes/peers/edit_participants_box.h"
#include "base/unixtime.h"
#include "ui/widgets/popup_menu.h" #include "ui/widgets/popup_menu.h"
#include "data/data_peer_values.h" #include "data/data_peer_values.h"
#include "data/data_channel.h" #include "data/data_channel.h"
@ -128,7 +129,7 @@ void GroupMembersWidget::refreshUserOnline(UserData *user) {
auto it = _membersByUser.find(user); auto it = _membersByUser.find(user);
if (it == _membersByUser.cend()) return; if (it == _membersByUser.cend()) return;
_now = unixtime(); _now = base::unixtime::now();
auto member = getMember(it.value()); auto member = getMember(it.value());
member->statusHasOnlineColor = !user->botInfo && Data::OnlineTextActive(user->onlineTill, _now); member->statusHasOnlineColor = !user->botInfo && Data::OnlineTextActive(user->onlineTill, _now);
@ -180,7 +181,7 @@ void GroupMembersWidget::updateItemStatusText(Item *item) {
} }
void GroupMembersWidget::refreshMembers() { void GroupMembersWidget::refreshMembers() {
_now = unixtime(); _now = base::unixtime::now();
if (const auto chat = peer()->asChat()) { if (const auto chat = peer()->asChat()) {
checkSelfAdmin(chat); checkSelfAdmin(chat);
if (chat->noParticipantInfo()) { if (chat->noParticipantInfo()) {
@ -421,7 +422,7 @@ auto GroupMembersWidget::computeMember(not_null<UserData*> user)
void GroupMembersWidget::onUpdateOnlineDisplay() { void GroupMembersWidget::onUpdateOnlineDisplay() {
if (_sortByOnline) { if (_sortByOnline) {
_now = unixtime(); _now = base::unixtime::now();
bool changed = false; bool changed = false;
for_const (auto item, items()) { for_const (auto item, items()) {

View File

@ -23,6 +23,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "history/history_message.h" #include "history/history_message.h"
#include "history/history.h" #include "history/history.h"
#include "calls/calls_instance.h" #include "calls/calls_instance.h"
#include "base/unixtime.h"
#include "ui/widgets/checkbox.h" #include "ui/widgets/checkbox.h"
#include "ui/wrap/padding_wrap.h" #include "ui/wrap/padding_wrap.h"
#include "ui/wrap/vertical_layout.h" #include "ui/wrap/vertical_layout.h"
@ -125,7 +126,7 @@ AdminLog::OwnedItem GenerateForwardedItem(
MTP_flags(FwdFlag::f_from_id), MTP_flags(FwdFlag::f_from_id),
MTP_int(history->session().userId()), MTP_int(history->session().userId()),
MTPstring(), // from_name MTPstring(), // from_name
MTP_int(unixtime()), MTP_int(base::unixtime::now()),
MTPint(), // channel_id MTPint(), // channel_id
MTPint(), // channel_post MTPint(), // channel_post
MTPstring(), // post_author MTPstring(), // post_author
@ -133,7 +134,7 @@ AdminLog::OwnedItem GenerateForwardedItem(
MTPint()), // saved_from_msg_id MTPint()), // saved_from_msg_id
MTPint(), // via_bot_id MTPint(), // via_bot_id
MTPint(), // reply_to_msg_id, MTPint(), // reply_to_msg_id,
MTP_int(unixtime()), // date MTP_int(base::unixtime::now()), // date
MTP_string(text), MTP_string(text),
MTPMessageMedia(), MTPMessageMedia(),
MTPReplyMarkup(), MTPReplyMarkup(),

View File

@ -11,6 +11,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_session.h" #include "data/data_session.h"
#include "core/file_utilities.h" #include "core/file_utilities.h"
#include "core/mime_type.h" #include "core/mime_type.h"
#include "base/unixtime.h"
#include "media/audio/media_audio.h" #include "media/audio/media_audio.h"
#include "media/clip/media_clip_reader.h" #include "media/clip/media_clip_reader.h"
#include "lottie/lottie_animation.h" #include "lottie/lottie_animation.h"
@ -217,7 +218,7 @@ SendMediaReady PreparePeerPhoto(PeerId peerId, QImage &&image) {
MTP_long(id), MTP_long(id),
MTP_long(0), MTP_long(0),
MTP_bytes(), MTP_bytes(),
MTP_int(unixtime()), MTP_int(base::unixtime::now()),
MTP_vector<MTPPhotoSize>(photoSizes), MTP_vector<MTPPhotoSize>(photoSizes),
MTP_int(MTP::maindc())); MTP_int(MTP::maindc()));
@ -280,7 +281,7 @@ SendMediaReady PrepareWallPaper(const QImage &image) {
MTP_long(id), MTP_long(id),
MTP_long(0), MTP_long(0),
MTP_bytes(), MTP_bytes(),
MTP_int(unixtime()), MTP_int(base::unixtime::now()),
MTP_string("image/jpeg"), MTP_string("image/jpeg"),
MTP_int(jpeg.size()), MTP_int(jpeg.size()),
MTP_vector<MTPPhotoSize>(sizes), MTP_vector<MTPPhotoSize>(sizes),
@ -929,7 +930,7 @@ void FileLoadTask::process() {
MTP_long(_id), MTP_long(_id),
MTP_long(0), MTP_long(0),
MTP_bytes(), MTP_bytes(),
MTP_int(unixtime()), MTP_int(base::unixtime::now()),
MTP_vector<MTPPhotoSize>(photoSizes), MTP_vector<MTPPhotoSize>(photoSizes),
MTP_int(MTP::maindc())); MTP_int(MTP::maindc()));
@ -959,7 +960,7 @@ void FileLoadTask::process() {
MTP_long(_id), MTP_long(_id),
MTP_long(0), MTP_long(0),
MTP_bytes(), MTP_bytes(),
MTP_int(unixtime()), MTP_int(base::unixtime::now()),
MTP_string(filemime), MTP_string(filemime),
MTP_int(filesize), MTP_int(filesize),
MTP_vector<MTPPhotoSize>(1, thumbnail.mtpSize), MTP_vector<MTPPhotoSize>(1, thumbnail.mtpSize),
@ -971,7 +972,7 @@ void FileLoadTask::process() {
MTP_long(_id), MTP_long(_id),
MTP_long(0), MTP_long(0),
MTP_bytes(), MTP_bytes(),
MTP_int(unixtime()), MTP_int(base::unixtime::now()),
MTP_string(filemime), MTP_string(filemime),
MTP_int(filesize), MTP_int(filesize),
MTP_vector<MTPPhotoSize>(1, thumbnail.mtpSize), MTP_vector<MTPPhotoSize>(1, thumbnail.mtpSize),

View File

@ -18,6 +18,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "history/history_message.h" #include "history/history_message.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "base/unixtime.h"
#include "auth_session.h" #include "auth_session.h"
#include "apiwrap.h" #include "apiwrap.h"
#include "styles/style_chat_helpers.h" #include "styles/style_chat_helpers.h"
@ -278,7 +279,7 @@ AdminLog::OwnedItem GenerateCommentItem(
flags, flags,
replyTo, replyTo,
viaBotId, viaBotId,
unixtime(), base::unixtime::now(),
history->session().userId(), history->session().userId(),
QString(), QString(),
TextWithEntities{ TextUtilities::Clean(data.comment) }); TextWithEntities{ TextUtilities::Clean(data.comment) });
@ -302,7 +303,7 @@ AdminLog::OwnedItem GenerateContactItem(
MTPMessageFwdHeader(), MTPMessageFwdHeader(),
MTP_int(viaBotId), MTP_int(viaBotId),
MTP_int(replyTo), MTP_int(replyTo),
MTP_int(unixtime()), MTP_int(base::unixtime::now()),
MTP_string(), MTP_string(),
MTP_messageMediaContact( MTP_messageMediaContact(
MTP_string(data.phone), MTP_string(data.phone),

View File

@ -19,6 +19,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/text_options.h" #include "ui/text_options.h"
#include "chat_helpers/message_field.h" #include "chat_helpers/message_field.h"
#include "chat_helpers/emoji_suggestions_widget.h" #include "chat_helpers/emoji_suggestions_widget.h"
#include "base/unixtime.h"
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "window/window_session_controller.h" #include "window/window_session_controller.h"
#include "storage/storage_media_prepare.h" #include "storage/storage_media_prepare.h"
@ -119,7 +120,7 @@ void EditInfoBox::setInnerFocus() {
QString FormatDateTime(TimeId value) { QString FormatDateTime(TimeId value) {
const auto now = QDateTime::currentDateTime(); const auto now = QDateTime::currentDateTime();
const auto date = ParseDateTime(value); const auto date = base::unixtime::parse(value);
if (date.date() == now.date()) { if (date.date() == now.date()) {
return tr::lng_mediaview_today( return tr::lng_mediaview_today(
tr::now, tr::now,
@ -149,7 +150,7 @@ QString NormalizeName(QString name) {
} }
Data::Draft OccupiedDraft(const QString &normalizedName) { Data::Draft OccupiedDraft(const QString &normalizedName) {
const auto now = unixtime(), till = now + kOccupyFor; const auto now = base::unixtime::now(), till = now + kOccupyFor;
return { return {
TextWithTags{ "t:" TextWithTags{ "t:"
+ QString::number(till) + QString::number(till)
@ -190,7 +191,7 @@ uint32 ParseOccupationTag(History *history) {
auto result = uint32(); auto result = uint32();
for (const auto &part : parts) { for (const auto &part : parts) {
if (part.startsWith(qstr("t:"))) { if (part.startsWith(qstr("t:"))) {
if (part.mid(2).toInt() >= unixtime()) { if (part.mid(2).toInt() >= base::unixtime::now()) {
valid = true; valid = true;
} else { } else {
return 0; return 0;
@ -220,7 +221,7 @@ QString ParseOccupationName(History *history) {
auto result = QString(); auto result = QString();
for (const auto &part : parts) { for (const auto &part : parts) {
if (part.startsWith(qstr("t:"))) { if (part.startsWith(qstr("t:"))) {
if (part.mid(2).toInt() >= unixtime()) { if (part.mid(2).toInt() >= base::unixtime::now()) {
valid = true; valid = true;
} else { } else {
return 0; return 0;
@ -254,7 +255,7 @@ TimeId OccupiedBySomeoneTill(History *history) {
auto result = TimeId(); auto result = TimeId();
for (const auto &part : parts) { for (const auto &part : parts) {
if (part.startsWith(qstr("t:"))) { if (part.startsWith(qstr("t:"))) {
if (part.mid(2).toInt() >= unixtime()) { if (part.mid(2).toInt() >= base::unixtime::now()) {
result = part.mid(2).toInt(); result = part.mid(2).toInt();
} else { } else {
return 0; return 0;
@ -330,7 +331,7 @@ void Helper::chatOccupiedUpdated(not_null<History*> history) {
} }
void Helper::checkOccupiedChats() { void Helper::checkOccupiedChats() {
const auto now = unixtime(); const auto now = base::unixtime::now();
while (!_occupiedChats.empty()) { while (!_occupiedChats.empty()) {
const auto nearest = ranges::min_element( const auto nearest = ranges::min_element(
_occupiedChats, _occupiedChats,

View File

@ -17,6 +17,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_keys.h" #include "lang/lang_keys.h"
#include "data/data_session.h" #include "data/data_session.h"
#include "data/data_channel.h" #include "data/data_channel.h"
#include "base/unixtime.h"
#include "window/window_session_controller.h" #include "window/window_session_controller.h"
#include "core/application.h" #include "core/application.h"
#include "mainwindow.h" #include "mainwindow.h"
@ -98,7 +99,7 @@ void System::schedule(History *history, HistoryItem *item) {
} }
auto delay = item->Has<HistoryMessageForwarded>() ? 500 : 100; auto delay = item->Has<HistoryMessageForwarded>() ? 500 : 100;
auto t = unixtime(); auto t = base::unixtime::now();
auto ms = crl::now(); auto ms = crl::now();
bool isOnline = App::main()->lastWasOnline(), otherNotOld = ((cOtherOnline() * 1000LL) + Global::OnlineCloudTimeout() > t * 1000LL); bool isOnline = App::main()->lastWasOnline(), otherNotOld = ((cOtherOnline() * 1000LL) + Global::OnlineCloudTimeout() > t * 1000LL);
bool otherLaterThanMe = (cOtherOnline() * 1000LL + (ms - App::main()->lastSetOnline()) > 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); auto ms = crl::now(), nextAlert = crl::time(0);
bool alert = false; bool alert = false;
int32 now = unixtime(); int32 now = base::unixtime::now();
for (auto i = _whenAlerts.begin(); i != _whenAlerts.end();) { for (auto i = _whenAlerts.begin(); i != _whenAlerts.end();) {
while (!i.value().isEmpty() && i.value().begin().key() <= ms) { while (!i.value().isEmpty() && i.value().begin().key() <= ms) {
const auto peer = i.key()->peer; const auto peer = i.key()->peer;

View File

@ -22,6 +22,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_chat.h" #include "data/data_chat.h"
#include "passport/passport_form_controller.h" #include "passport/passport_form_controller.h"
#include "core/shortcuts.h" #include "core/shortcuts.h"
#include "base/unixtime.h"
#include "boxes/calendar_box.h" #include "boxes/calendar_box.h"
#include "mainwidget.h" #include "mainwidget.h"
#include "mainwindow.h" #include "mainwindow.h"
@ -492,13 +493,13 @@ void SessionController::showJumpToDate(Dialogs::Key chat, QDate requestedDate) {
} }
} }
} else if (history->chatListTimeId() != 0) { } 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 //} else if (const auto feed = chat.feed()) { // #feed
// if (chatScrollPosition(feed)) { // #TODO feeds save position // if (chatScrollPosition(feed)) { // #TODO feeds save position
// } else if (feed->chatListTimeId() != 0) { // } else if (feed->chatListTimeId() != 0) {
// return ParseDateTime(feed->chatListTimeId()).date(); // return base::unixtime::parse(feed->chatListTimeId()).date();
// } // }
} }
return QDate(); return QDate();
@ -509,11 +510,11 @@ void SessionController::showJumpToDate(Dialogs::Key chat, QDate requestedDate) {
history = channel->owner().historyLoaded(channel); history = channel->owner().historyLoaded(channel);
} }
if (history && history->chatListTimeId() != 0) { 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 //} else if (const auto feed = chat.feed()) { // #feed
// if (feed->chatListTimeId() != 0) { // if (feed->chatListTimeId() != 0) {
// return ParseDateTime(feed->chatListTimeId()).date(); // return base::unixtime::parse(feed->chatListTimeId()).date();
// } // }
} }
return QDate::currentDate(); return QDate::currentDate();

View File

@ -80,6 +80,8 @@
'<(src_loc)/base/unique_any.h', '<(src_loc)/base/unique_any.h',
'<(src_loc)/base/unique_function.h', '<(src_loc)/base/unique_function.h',
'<(src_loc)/base/unique_qptr.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/value_ordering.h',
'<(src_loc)/base/variant.h', '<(src_loc)/base/variant.h',
'<(src_loc)/base/virtual_method.h', '<(src_loc)/base/virtual_method.h',