Merge remote-tracking branch 'td/master'

This commit is contained in:
Andrea Cavalli 2021-10-20 02:17:16 +02:00
commit 98244d1346
241 changed files with 1494 additions and 1472 deletions

View File

@ -58,8 +58,7 @@ class RingBench final : public td::Benchmark {
} else { } else {
// TODO: it is three times faster than send_event // TODO: it is three times faster than send_event
// maybe send event could be further optimized? // maybe send event could be further optimized?
::td::Scheduler::instance()->hack(static_cast<td::ActorId<Actor>>(next_actor), next_actor.get_actor_unsafe()->raw_event(td::Event::raw(static_cast<td::uint32>(n - 1)).data);
td::Event::raw(static_cast<td::uint32>(n - 1)));
} }
} else if (type == 4) { } else if (type == 4) {
send_lambda(next_actor, [n, ptr = next_actor.get_actor_unsafe()] { ptr->pass(n - 1); }); send_lambda(next_actor, [n, ptr = next_actor.get_actor_unsafe()] { ptr->pass(n - 1); });

View File

@ -22,7 +22,7 @@ class HttpReaderBench final : public td::Benchmark {
} }
void run(int n) final { void run(int n) final {
int cnt = static_cast<int>(block_size / http_query.size()); auto cnt = static_cast<int>(block_size / http_query.size());
td::HttpQuery q; td::HttpQuery q;
int parsed = 0; int parsed = 0;
int sent = 0; int sent = 0;
@ -58,7 +58,7 @@ class BufferBench final : public td::Benchmark {
} }
void run(int n) final { void run(int n) final {
int cnt = static_cast<int>(block_size / http_query.size()); auto cnt = static_cast<int>(block_size / http_query.size());
for (int i = 0; i < n; i += cnt) { for (int i = 0; i < n; i += cnt) {
for (int j = 0; j < cnt; j++) { for (int j = 0; j < cnt; j++) {
writer_.append(http_query); writer_.append(http_query);
@ -84,7 +84,7 @@ class FindBoundaryBench final : public td::Benchmark {
} }
void run(int n) final { void run(int n) final {
int cnt = static_cast<int>(block_size / http_query.size()); auto cnt = static_cast<int>(block_size / http_query.size());
for (int i = 0; i < n; i += cnt) { for (int i = 0; i < n; i += cnt) {
for (int j = 0; j < cnt; j++) { for (int j = 0; j < cnt; j++) {
writer_.append(http_query); writer_.append(http_query);

View File

@ -105,7 +105,8 @@ BENCH(NewObj, "new struct, then delete") {
#if !TD_THREAD_UNSUPPORTED #if !TD_THREAD_UNSUPPORTED
BENCH(ThreadNew, "new struct, then delete in 2 threads") { BENCH(ThreadNew, "new struct, then delete in 2 threads") {
NewObjBench a, b; NewObjBench a;
NewObjBench b;
td::thread ta([&] { a.run(n / 2); }); td::thread ta([&] { a.run(n / 2); });
td::thread tb([&] { b.run(n - n / 2); }); td::thread tb([&] { b.run(n - n / 2); });
ta.join(); ta.join();

View File

@ -591,7 +591,7 @@ class QueueBenchmark2 final : public td::Benchmark {
void server_process(qvalue_t value) { void server_process(qvalue_t value) {
int no = value & 0x00FFFFFF; int no = value & 0x00FFFFFF;
int co = static_cast<int>(static_cast<unsigned int>(value) >> 24); auto co = static_cast<int>(static_cast<td::uint32>(value) >> 24);
// std::fprintf(stderr, "-->%d %d\n", co, no); // std::fprintf(stderr, "-->%d %d\n", co, no);
if (co < 0 || co >= connections_n || no != server_conn[co]++) { if (co < 0 || co >= connections_n || no != server_conn[co]++) {
std::fprintf(stderr, "%d %d\n", co, no); std::fprintf(stderr, "%d %d\n", co, no);
@ -632,7 +632,7 @@ class QueueBenchmark2 final : public td::Benchmark {
void client_process(qvalue_t value) { void client_process(qvalue_t value) {
int no = value & 0x00FFFFFF; int no = value & 0x00FFFFFF;
int co = static_cast<int>(static_cast<unsigned int>(value) >> 24); auto co = static_cast<int>(static_cast<td::uint32>(value) >> 24);
// std::fprintf(stderr, "<--%d %d\n", co, no); // std::fprintf(stderr, "<--%d %d\n", co, no);
if (co < 0 || co >= connections_n || no != client_conn[co]++) { if (co < 0 || co >= connections_n || no != client_conn[co]++) {
std::fprintf(stderr, "%d %d\n", co, no); std::fprintf(stderr, "%d %d\n", co, no);
@ -733,7 +733,7 @@ class QueueBenchmark final : public td::Benchmark {
while (active_connections > 0) { while (active_connections > 0) {
qvalue_t value = server.get(); qvalue_t value = server.get();
int no = value & 0x00FFFFFF; int no = value & 0x00FFFFFF;
int co = static_cast<int>(value >> 24); auto co = static_cast<int>(value >> 24);
// std::fprintf(stderr, "-->%d %d\n", co, no); // std::fprintf(stderr, "-->%d %d\n", co, no);
if (co < 0 || co >= connections_n || no != conn[co]++) { if (co < 0 || co >= connections_n || no != conn[co]++) {
std::fprintf(stderr, "%d %d\n", co, no); std::fprintf(stderr, "%d %d\n", co, no);
@ -764,7 +764,7 @@ class QueueBenchmark final : public td::Benchmark {
while (active_connections > 0) { while (active_connections > 0) {
qvalue_t value = client.get(); qvalue_t value = client.get();
int no = value & 0x00FFFFFF; int no = value & 0x00FFFFFF;
int co = static_cast<int>(value >> 24); auto co = static_cast<int>(value >> 24);
// std::fprintf(stderr, "<--%d %d\n", co, no); // std::fprintf(stderr, "<--%d %d\n", co, no);
if (co < 0 || co >= connections_n || no != conn[co]++) { if (co < 0 || co >= connections_n || no != conn[co]++) {
std::fprintf(stderr, "%d %d\n", co, no); std::fprintf(stderr, "%d %d\n", co, no);
@ -797,7 +797,7 @@ class QueueBenchmark final : public td::Benchmark {
for (int i = 0; i < connections_n; i++) { for (int i = 0; i < connections_n; i++) {
qvalue_t value = client.get(); qvalue_t value = client.get();
int no = value & 0x00FFFFFF; int no = value & 0x00FFFFFF;
int co = static_cast<int>(value >> 24); auto co = static_cast<int>(value >> 24);
// std::fprintf(stderr, "<--%d %d\n", co, no); // std::fprintf(stderr, "<--%d %d\n", co, no);
if (co < 0 || co >= connections_n || no != conn[co]++) { if (co < 0 || co >= connections_n || no != conn[co]++) {
std::fprintf(stderr, "%d %d\n", co, no); std::fprintf(stderr, "%d %d\n", co, no);

View File

@ -50,10 +50,10 @@ static jint Client_nativeClientReceive(JNIEnv *env, jclass clazz, jintArray clie
auto *manager = get_manager(); auto *manager = get_manager();
auto response = manager->receive(timeout); auto response = manager->receive(timeout);
while (response.object) { while (response.object) {
jint client_id = static_cast<jint>(response.client_id); auto client_id = static_cast<jint>(response.client_id);
env->SetIntArrayRegion(client_ids, result_size, 1, &client_id); env->SetIntArrayRegion(client_ids, result_size, 1, &client_id);
jlong request_id = static_cast<jlong>(response.request_id); auto request_id = static_cast<jlong>(response.request_id);
env->SetLongArrayRegion(ids, result_size, 1, &request_id); env->SetLongArrayRegion(ids, result_size, 1, &request_id);
jobject object; jobject object;

View File

@ -58,7 +58,7 @@ static int fast_backtrace(void **buffer, int size) {
void *ip; void *ip;
}; };
stack_frame *bp = reinterpret_cast<stack_frame *>(get_bp()); auto *bp = reinterpret_cast<stack_frame *>(get_bp());
int i = 0; int i = 0;
while (i < size && while (i < size &&
#if TD_LINUX #if TD_LINUX
@ -153,7 +153,7 @@ std::size_t get_ht_size() {
std::int32_t get_ht_pos(const Backtrace &bt, bool force = false) { std::int32_t get_ht_pos(const Backtrace &bt, bool force = false) {
auto hash = get_hash(bt); auto hash = get_hash(bt);
std::int32_t pos = static_cast<std::int32_t>(hash % ht.size()); auto pos = static_cast<std::int32_t>(hash % ht.size());
bool was_overflow = false; bool was_overflow = false;
while (true) { while (true) {
auto pos_hash = ht[pos].hash.load(); auto pos_hash = ht[pos].hash.load();
@ -237,7 +237,7 @@ static void *malloc_with_frame(std::size_t size, const Backtrace &frame) {
} }
static malloc_info *get_info(void *data_void) { static malloc_info *get_info(void *data_void) {
char *data = static_cast<char *>(data_void); auto *data = static_cast<char *>(data_void);
auto *buf = data - RESERVED_SIZE; auto *buf = data - RESERVED_SIZE;
auto *info = reinterpret_cast<malloc_info *>(buf); auto *info = reinterpret_cast<malloc_info *>(buf);

View File

@ -261,9 +261,8 @@ std::string TD_TL_writer::gen_constructor_parameter(int field_num, const std::st
} else if (field_type == "UInt128 " || field_type == "UInt256 " || field_type == "string " || } else if (field_type == "UInt128 " || field_type == "UInt256 " || field_type == "string " ||
(string_type == bytes_type && field_type == "bytes ")) { (string_type == bytes_type && field_type == "bytes ")) {
res += field_type + "const &"; res += field_type + "const &";
} else if (field_type.compare(0, 5, "array") == 0 || field_type == "bytes ") { } else if (field_type.compare(0, 5, "array") == 0 || field_type == "bytes " ||
res += field_type + "&&"; field_type.compare(0, 10, "object_ptr") == 0) {
} else if (field_type.compare(0, 10, "object_ptr") == 0) {
res += field_type + "&&"; res += field_type + "&&";
} else { } else {
assert(false && "unreachable"); assert(false && "unreachable");

View File

@ -78,7 +78,7 @@ bool AuthData::update_server_time_difference(double diff) {
} else { } else {
return false; return false;
} }
LOG(DEBUG) << "SERVER_TIME: " << format::as_hex(static_cast<int>(get_server_time(Time::now_cached()))); LOG(DEBUG) << "SERVER_TIME: " << format::as_hex(static_cast<int32>(get_server_time(Time::now_cached())));
return true; return true;
} }
@ -100,7 +100,7 @@ std::vector<ServerSalt> AuthData::get_future_salts() const {
int64 AuthData::next_message_id(double now) { int64 AuthData::next_message_id(double now) {
double server_time = get_server_time(now); double server_time = get_server_time(now);
int64 t = static_cast<int64>(server_time * (1ll << 32)); auto t = static_cast<int64>(server_time * (1ll << 32));
// randomize lower bits for clocks with low precision // randomize lower bits for clocks with low precision
// TODO(perf) do not do this for systems with good precision?.. // TODO(perf) do not do this for systems with good precision?..
@ -119,13 +119,13 @@ int64 AuthData::next_message_id(double now) {
bool AuthData::is_valid_outbound_msg_id(int64 id, double now) const { bool AuthData::is_valid_outbound_msg_id(int64 id, double now) const {
double server_time = get_server_time(now); double server_time = get_server_time(now);
auto id_time = static_cast<double>(id / (1ll << 32)); auto id_time = static_cast<double>(id) / static_cast<double>(1ll << 32);
return server_time - 300 / 2 < id_time && id_time < server_time + 60 / 2; return server_time - 300 / 2 < id_time && id_time < server_time + 30;
} }
bool AuthData::is_valid_inbound_msg_id(int64 id, double now) const { bool AuthData::is_valid_inbound_msg_id(int64 id, double now) const {
double server_time = get_server_time(now); double server_time = get_server_time(now);
auto id_time = static_cast<double>(id / (1ll << 32)); auto id_time = static_cast<double>(id) / static_cast<double>(1ll << 32);
return server_time - 300 < id_time && id_time < server_time + 30; return server_time - 300 < id_time && id_time < server_time + 30;
} }

View File

@ -24,7 +24,7 @@ class ConnectionManager : public Actor {
ConnectionToken(const ConnectionToken &) = delete; ConnectionToken(const ConnectionToken &) = delete;
ConnectionToken &operator=(const ConnectionToken &) = delete; ConnectionToken &operator=(const ConnectionToken &) = delete;
ConnectionToken(ConnectionToken &&) = default; ConnectionToken(ConnectionToken &&) = default;
ConnectionToken &operator=(ConnectionToken &&other) { ConnectionToken &operator=(ConnectionToken &&other) noexcept {
reset(); reset();
connection_manager_ = std::move(other.connection_manager_); connection_manager_ = std::move(other.connection_manager_);
return *this; return *this;

View File

@ -192,8 +192,9 @@ class CryptoImpl {
public: public:
CryptoImpl(const vector<MtprotoQuery> &to_send, Slice header, vector<int64> &&to_ack, int64 ping_id, int ping_timeout, CryptoImpl(const vector<MtprotoQuery> &to_send, Slice header, vector<int64> &&to_ack, int64 ping_id, int ping_timeout,
int max_delay, int max_after, int max_wait, int future_salt_n, vector<int64> get_info, int max_delay, int max_after, int max_wait, int future_salt_n, vector<int64> get_info,
vector<int64> resend, vector<int64> cancel, bool destroy_key, AuthData *auth_data, uint64 *container_id, vector<int64> resend, const vector<int64> &cancel, bool destroy_key, AuthData *auth_data,
uint64 *get_info_id, uint64 *resend_id, uint64 *ping_message_id, uint64 *parent_message_id) uint64 *container_id, uint64 *get_info_id, uint64 *resend_id, uint64 *ping_message_id,
uint64 *parent_message_id)
: query_storer_(to_send, header) : query_storer_(to_send, header)
, ack_empty_(to_ack.empty()) , ack_empty_(to_ack.empty())
, ack_storer_(!ack_empty_, mtproto_api::msgs_ack(std::move(to_ack)), auth_data) , ack_storer_(!ack_empty_, mtproto_api::msgs_ack(std::move(to_ack)), auth_data)
@ -206,7 +207,7 @@ class CryptoImpl {
, resend_storer_(resend_not_empty_, mtproto_api::msg_resend_req(std::move(resend)), auth_data, true) , resend_storer_(resend_not_empty_, mtproto_api::msg_resend_req(std::move(resend)), auth_data, true)
, cancel_not_empty_(!cancel.empty()) , cancel_not_empty_(!cancel.empty())
, cancel_cnt_(static_cast<int32>(cancel.size())) , cancel_cnt_(static_cast<int32>(cancel.size()))
, cancel_storer_(cancel_not_empty_, std::move(cancel), auth_data, true) , cancel_storer_(cancel_not_empty_, cancel, auth_data, true)
, destroy_key_storer_(destroy_key, mtproto_api::destroy_auth_key(), auth_data, true) , destroy_key_storer_(destroy_key, mtproto_api::destroy_auth_key(), auth_data, true)
, tmp_storer_(query_storer_, ack_storer_) , tmp_storer_(query_storer_, ack_storer_)
, tmp2_storer_(tmp_storer_, http_wait_storer_) , tmp2_storer_(tmp_storer_, http_wait_storer_)

View File

@ -95,7 +95,8 @@ Status AuthKeyHandshake::on_res_pq(Slice message, Callback *connection, PublicRs
} }
auto rsa_key = r_rsa_key.move_as_ok(); auto rsa_key = r_rsa_key.move_as_ok();
string p, q; string p;
string q;
if (pq_factorize(res_pq->pq_, &p, &q) == -1) { if (pq_factorize(res_pq->pq_, &p, &q) == -1) {
return Status::Error("Failed to factorize"); return Status::Error("Failed to factorize");
} }
@ -129,7 +130,7 @@ Status AuthKeyHandshake::on_res_pq(Slice message, Callback *connection, PublicRs
string aes_key(32, '\0'); string aes_key(32, '\0');
Random::secure_bytes(MutableSlice(aes_key)); Random::secure_bytes(MutableSlice(aes_key));
string data_with_hash = data + sha256(aes_key + data); string data_with_hash = PSTRING() << data << sha256(aes_key + data);
std::reverse(data_with_hash.begin(), data_with_hash.begin() + data.size()); std::reverse(data_with_hash.begin(), data_with_hash.begin() + data.size());
string decrypted_data(256, '\0'); string decrypted_data(256, '\0');
@ -246,17 +247,32 @@ Status AuthKeyHandshake::on_server_dh_params(Slice message, Callback *connection
Status AuthKeyHandshake::on_dh_gen_response(Slice message, Callback *connection) { Status AuthKeyHandshake::on_dh_gen_response(Slice message, Callback *connection) {
TRY_RESULT(answer, fetch_result<mtproto_api::set_client_DH_params>(message, false)); TRY_RESULT(answer, fetch_result<mtproto_api::set_client_DH_params>(message, false));
switch (answer->get_id()) { switch (answer->get_id()) {
case mtproto_api::dh_gen_ok::ID: case mtproto_api::dh_gen_ok::ID: {
auto dh_gen_ok = move_tl_object_as<mtproto_api::dh_gen_ok>(answer);
if (dh_gen_ok->nonce_ != nonce_) {
return Status::Error("Nonce mismatch");
}
if (dh_gen_ok->server_nonce_ != server_nonce_) {
return Status::Error("Server nonce mismatch");
}
UInt<160> auth_key_sha1;
sha1(auth_key_.key(), auth_key_sha1.raw);
auto new_nonce_hash = sha1(PSLICE() << new_nonce_.as_slice() << '\x01' << auth_key_sha1.as_slice().substr(0, 8));
if (dh_gen_ok->new_nonce_hash1_.as_slice() != Slice(new_nonce_hash).substr(4)) {
return Status::Error("New nonce hash mismatch");
}
state_ = Finish; state_ = Finish;
break; return Status::OK();
}
case mtproto_api::dh_gen_fail::ID: case mtproto_api::dh_gen_fail::ID:
return Status::Error("DhGenFail"); return Status::Error("DhGenFail");
case mtproto_api::dh_gen_retry::ID: case mtproto_api::dh_gen_retry::ID:
return Status::Error("DhGenRetry"); return Status::Error("DhGenRetry");
default: default:
UNREACHABLE();
return Status::Error("Unknown set_client_DH_params response"); return Status::Error("Unknown set_client_DH_params response");
} }
return Status::OK();
} }
void AuthKeyHandshake::send(Callback *connection, const Storer &storer) { void AuthKeyHandshake::send(Callback *connection, const Storer &storer) {

View File

@ -97,7 +97,7 @@ class AuthKeyHandshake {
static string store_object(const mtproto_api::Object &object); static string store_object(const mtproto_api::Object &object);
void send(Callback *connection, const Storer &storer); void send(Callback *connection, const Storer &storer);
void do_send(Callback *connection, const Storer &storer); static void do_send(Callback *connection, const Storer &storer);
Status on_start(Callback *connection) TD_WARN_UNUSED_RESULT; Status on_start(Callback *connection) TD_WARN_UNUSED_RESULT;
Status on_res_pq(Slice message, Callback *connection, PublicRsaKeyInterface *public_rsa_key) TD_WARN_UNUSED_RESULT; Status on_res_pq(Slice message, Callback *connection, PublicRsaKeyInterface *public_rsa_key) TD_WARN_UNUSED_RESULT;

View File

@ -65,7 +65,7 @@ class HandshakeConnection final
} }
Status on_raw_packet(const PacketInfo &packet_info, BufferSlice packet) final { Status on_raw_packet(const PacketInfo &packet_info, BufferSlice packet) final {
if (packet_info.no_crypto_flag == false) { if (!packet_info.no_crypto_flag) {
return Status::Error("Expected not encrypted packet"); return Status::Error("Expected not encrypted packet");
} }

View File

@ -19,7 +19,7 @@
namespace td { namespace td {
namespace mtproto { namespace mtproto {
ActorOwn<> create_ping_actor(string debug, unique_ptr<RawConnection> raw_connection, unique_ptr<AuthData> auth_data, ActorOwn<> create_ping_actor(Slice actor_name, unique_ptr<RawConnection> raw_connection, unique_ptr<AuthData> auth_data,
Promise<unique_ptr<RawConnection>> promise, ActorShared<> parent) { Promise<unique_ptr<RawConnection>> promise, ActorShared<> parent) {
class PingActor final : public Actor { class PingActor final : public Actor {
public: public:
@ -99,7 +99,7 @@ ActorOwn<> create_ping_actor(string debug, unique_ptr<RawConnection> raw_connect
} }
} }
}; };
return ActorOwn<>(create_actor<PingActor>(PSLICE() << "PingActor<" << debug << ">", std::move(raw_connection), return ActorOwn<>(create_actor<PingActor>(PSLICE() << "PingActor<" << actor_name << ">", std::move(raw_connection),
std::move(auth_data), std::move(promise), std::move(parent))); std::move(auth_data), std::move(promise), std::move(parent)));
} }

View File

@ -17,7 +17,7 @@
namespace td { namespace td {
namespace mtproto { namespace mtproto {
ActorOwn<> create_ping_actor(string debug, unique_ptr<RawConnection> raw_connection, unique_ptr<AuthData> auth_data, ActorOwn<> create_ping_actor(Slice actor_name, unique_ptr<RawConnection> raw_connection, unique_ptr<AuthData> auth_data,
Promise<unique_ptr<RawConnection>> promise, ActorShared<> parent); Promise<unique_ptr<RawConnection>> promise, ActorShared<> parent);
} // namespace mtproto } // namespace mtproto

View File

@ -37,7 +37,7 @@ class RawConnectionDefault final : public RawConnection {
public: public:
RawConnectionDefault(SocketFd socket_fd, TransportType transport_type, unique_ptr<StatsCallback> stats_callback) RawConnectionDefault(SocketFd socket_fd, TransportType transport_type, unique_ptr<StatsCallback> stats_callback)
: socket_fd_(std::move(socket_fd)) : socket_fd_(std::move(socket_fd))
, transport_(create_transport(transport_type)) , transport_(create_transport(std::move(transport_type)))
, stats_callback_(std::move(stats_callback)) { , stats_callback_(std::move(stats_callback)) {
transport_->init(&socket_fd_.input_buffer(), &socket_fd_.output_buffer()); transport_->init(&socket_fd_.input_buffer(), &socket_fd_.output_buffer());
} }

View File

@ -48,7 +48,7 @@ class RawConnection {
virtual bool can_send() const = 0; virtual bool can_send() const = 0;
virtual TransportType get_transport_type() const = 0; virtual TransportType get_transport_type() const = 0;
virtual void send_crypto(const Storer &storer, int64 session_id, int64 salt, const AuthKey &auth_key, virtual void send_crypto(const Storer &storer, int64 session_id, int64 salt, const AuthKey &auth_key,
uint64 quick_ack_token = 0) = 0; uint64 quick_ack_token) = 0;
virtual uint64 send_no_crypto(const Storer &storer) = 0; virtual uint64 send_no_crypto(const Storer &storer) = 0;
virtual PollableFdInfo &get_poll_info() = 0; virtual PollableFdInfo &get_poll_info() = 0;

View File

@ -893,7 +893,8 @@ void SessionConnection::flush_packet() {
} }
} }
size_t send_till = 0, send_size = 0; size_t send_till = 0;
size_t send_size = 0;
// send at most 1020 queries, of total size 2^15 // send at most 1020 queries, of total size 2^15
// don't send anything if have no salt // don't send anything if have no salt
if (has_salt) { if (has_salt) {

View File

@ -212,7 +212,8 @@ class SessionConnection final
}; };
} }
Status parse_message(TlParser &parser, MsgInfo *info, Slice *packet, bool crypto_flag = true) TD_WARN_UNUSED_RESULT; static Status parse_message(TlParser &parser, MsgInfo *info, Slice *packet,
bool crypto_flag = true) TD_WARN_UNUSED_RESULT;
Status parse_packet(TlParser &parser) TD_WARN_UNUSED_RESULT; Status parse_packet(TlParser &parser) TD_WARN_UNUSED_RESULT;
Status on_packet_container(const MsgInfo &info, Slice packet) TD_WARN_UNUSED_RESULT; Status on_packet_container(const MsgInfo &info, Slice packet) TD_WARN_UNUSED_RESULT;
Status on_packet_rpc_result(const MsgInfo &info, Slice packet) TD_WARN_UNUSED_RESULT; Status on_packet_rpc_result(const MsgInfo &info, Slice packet) TD_WARN_UNUSED_RESULT;

View File

@ -272,8 +272,8 @@ void ObfuscatedTransport::do_write_tls(BufferBuilder &&builder) {
do_write(builder.extract()); do_write(builder.extract());
} }
void ObfuscatedTransport::do_write(BufferSlice &&slice) { void ObfuscatedTransport::do_write(BufferSlice &&message) {
output_->append(std::move(slice)); output_->append(std::move(message));
} }
} // namespace tcp } // namespace tcp

View File

@ -128,8 +128,8 @@ class OldTransport final : public IStreamTransport {
class ObfuscatedTransport final : public IStreamTransport { class ObfuscatedTransport final : public IStreamTransport {
public: public:
ObfuscatedTransport(int16 dc_id, const ProxySecret &secret) ObfuscatedTransport(int16 dc_id, ProxySecret secret)
: dc_id_(dc_id), secret_(secret), impl_(secret_.use_random_padding()) { : dc_id_(dc_id), secret_(std::move(secret)), impl_(secret_.use_random_padding()) {
} }
Result<size_t> read_next(BufferSlice *message, uint32 *quick_ack) final TD_WARN_UNUSED_RESULT; Result<size_t> read_next(BufferSlice *message, uint32 *quick_ack) final TD_WARN_UNUSED_RESULT;
@ -172,6 +172,7 @@ class ObfuscatedTransport final : public IStreamTransport {
TransportType get_type() const final { TransportType get_type() const final {
return TransportType{TransportType::ObfuscatedTcp, dc_id_, secret_}; return TransportType{TransportType::ObfuscatedTcp, dc_id_, secret_};
} }
bool use_random_padding() const final { bool use_random_padding() const final {
return secret_.use_random_padding(); return secret_.use_random_padding();
} }

View File

@ -162,7 +162,7 @@ void AuthManager::check_bot_token(uint64 query_id, string bot_token) {
} }
on_new_query(query_id); on_new_query(query_id);
bot_token_ = bot_token; bot_token_ = std::move(bot_token);
was_check_bot_token_ = true; was_check_bot_token_ = true;
start_net_query(NetQueryType::BotAuthentication, start_net_query(NetQueryType::BotAuthentication,
G()->net_query_creator().create_unauth( G()->net_query_creator().create_unauth(
@ -258,8 +258,8 @@ void AuthManager::set_phone_number(uint64 query_id, string phone_number,
on_new_query(query_id); on_new_query(query_id);
start_net_query(NetQueryType::SendCode, G()->net_query_creator().create_unauth( start_net_query(NetQueryType::SendCode, G()->net_query_creator().create_unauth(send_code_helper_.send_code(
send_code_helper_.send_code(phone_number, settings, api_id_, api_hash_))); std::move(phone_number), settings, api_id_, api_hash_)));
} }
void AuthManager::resend_authentication_code(uint64 query_id) { void AuthManager::resend_authentication_code(uint64 query_id) {
@ -425,8 +425,8 @@ void AuthManager::on_query_error(Status status) {
on_query_error(id, std::move(status)); on_query_error(id, std::move(status));
} }
void AuthManager::on_query_error(uint64 id, Status status) { void AuthManager::on_query_error(uint64 query_id, Status status) {
send_closure(G()->td(), &Td::send_error, id, std::move(status)); send_closure(G()->td(), &Td::send_error, query_id, std::move(status));
} }
void AuthManager::on_query_ok() { void AuthManager::on_query_ok() {

View File

@ -126,15 +126,16 @@ class AuthManager final : public NetActor {
TermsOfService terms_of_service_; TermsOfService terms_of_service_;
DbState() = default; DbState() = default;
static DbState wait_code(int32 api_id, string api_hash, SendCodeHelper send_code_helper) { static DbState wait_code(int32 api_id, string api_hash, SendCodeHelper send_code_helper) {
DbState state(State::WaitCode, api_id, api_hash); DbState state(State::WaitCode, api_id, std::move(api_hash));
state.send_code_helper_ = std::move(send_code_helper); state.send_code_helper_ = std::move(send_code_helper);
return state; return state;
} }
static DbState wait_qr_code_confirmation(int32 api_id, string api_hash, vector<UserId> other_user_ids, static DbState wait_qr_code_confirmation(int32 api_id, string api_hash, vector<UserId> other_user_ids,
string login_token, double login_token_expires_at) { string login_token, double login_token_expires_at) {
DbState state(State::WaitQrCodeConfirmation, api_id, api_hash); DbState state(State::WaitQrCodeConfirmation, api_id, std::move(api_hash));
state.other_user_ids_ = std::move(other_user_ids); state.other_user_ids_ = std::move(other_user_ids);
state.login_token_ = std::move(login_token); state.login_token_ = std::move(login_token);
state.login_token_expires_at_ = login_token_expires_at; state.login_token_expires_at_ = login_token_expires_at;
@ -142,14 +143,14 @@ class AuthManager final : public NetActor {
} }
static DbState wait_password(int32 api_id, string api_hash, WaitPasswordState wait_password_state) { static DbState wait_password(int32 api_id, string api_hash, WaitPasswordState wait_password_state) {
DbState state(State::WaitPassword, api_id, api_hash); DbState state(State::WaitPassword, api_id, std::move(api_hash));
state.wait_password_state_ = std::move(wait_password_state); state.wait_password_state_ = std::move(wait_password_state);
return state; return state;
} }
static DbState wait_registration(int32 api_id, string api_hash, SendCodeHelper send_code_helper, static DbState wait_registration(int32 api_id, string api_hash, SendCodeHelper send_code_helper,
TermsOfService terms_of_service) { TermsOfService terms_of_service) {
DbState state(State::WaitRegistration, api_id, api_hash); DbState state(State::WaitRegistration, api_id, std::move(api_hash));
state.send_code_helper_ = std::move(send_code_helper); state.send_code_helper_ = std::move(send_code_helper);
state.terms_of_service_ = std::move(terms_of_service); state.terms_of_service_ = std::move(terms_of_service);
return state; return state;
@ -161,8 +162,8 @@ class AuthManager final : public NetActor {
void parse(ParserT &parser); void parse(ParserT &parser);
private: private:
DbState(State state, int32 api_id, string api_hash) DbState(State state, int32 api_id, string &&api_hash)
: state_(state), api_id_(api_id), api_hash_(api_hash), state_timestamp_(Timestamp::now()) { : state_(state), api_id_(api_id), api_hash_(std::move(api_hash)), state_timestamp_(Timestamp::now()) {
} }
}; };
@ -216,7 +217,6 @@ class AuthManager final : public NetActor {
void on_new_query(uint64 query_id); void on_new_query(uint64 query_id);
void on_query_error(Status status); void on_query_error(Status status);
void on_query_error(uint64 id, Status status);
void on_query_ok(); void on_query_ok();
void start_net_query(NetQueryType net_query_type, NetQueryPtr net_query); void start_net_query(NetQueryType net_query_type, NetQueryPtr net_query);
@ -232,7 +232,7 @@ class AuthManager final : public NetActor {
void on_get_password_result(NetQueryPtr &result); void on_get_password_result(NetQueryPtr &result);
void on_request_password_recovery_result(NetQueryPtr &result); void on_request_password_recovery_result(NetQueryPtr &result);
void on_check_password_recovery_code_result(NetQueryPtr &result); void on_check_password_recovery_code_result(NetQueryPtr &result);
void on_authentication_result(NetQueryPtr &result, bool expected_flag); void on_authentication_result(NetQueryPtr &result, bool is_from_current_query);
void on_log_out_result(NetQueryPtr &result); void on_log_out_result(NetQueryPtr &result);
void on_delete_account_result(NetQueryPtr &result); void on_delete_account_result(NetQueryPtr &result);
void on_get_login_token(tl_object_ptr<telegram_api::auth_LoginToken> login_token); void on_get_login_token(tl_object_ptr<telegram_api::auth_LoginToken> login_token);
@ -242,7 +242,9 @@ class AuthManager final : public NetActor {
void update_state(State new_state, bool force = false, bool should_save_state = true); void update_state(State new_state, bool force = false, bool should_save_state = true);
tl_object_ptr<td_api::AuthorizationState> get_authorization_state_object(State authorization_state) const; tl_object_ptr<td_api::AuthorizationState> get_authorization_state_object(State authorization_state) const;
void send_ok(uint64 query_id);
static void send_ok(uint64 query_id);
static void on_query_error(uint64 query_id, Status status);
void start_up() final; void start_up() final;
void tear_down() final; void tear_down() final;

View File

@ -453,7 +453,7 @@ void BackgroundManager::get_backgrounds(bool for_dark_theme,
} }
Result<string> BackgroundManager::get_background_url(const string &name, Result<string> BackgroundManager::get_background_url(const string &name,
td_api::object_ptr<td_api::BackgroundType> background_type) const { td_api::object_ptr<td_api::BackgroundType> background_type) {
TRY_RESULT(type, BackgroundType::get_background_type(background_type.get())); TRY_RESULT(type, BackgroundType::get_background_type(background_type.get()));
auto url = PSTRING() << G()->shared_config().get_option_string("t_me_url", "https://t.me/") << "bg/"; auto url = PSTRING() << G()->shared_config().get_option_string("t_me_url", "https://t.me/") << "bg/";
auto link = type.get_link(); auto link = type.get_link();
@ -526,7 +526,7 @@ std::pair<BackgroundId, BackgroundType> BackgroundManager::search_background(con
if (queries.size() == 1) { if (queries.size() == 1) {
LOG(INFO) << "Trying to load background " << slug << " from database"; LOG(INFO) << "Trying to load background " << slug << " from database";
G()->td_db()->get_sqlite_pmc()->get( G()->td_db()->get_sqlite_pmc()->get(
get_background_name_database_key(slug), PromiseCreator::lambda([slug](string value) { get_background_name_database_key(slug), PromiseCreator::lambda([slug](string value) mutable {
send_closure(G()->background_manager(), &BackgroundManager::on_load_background_from_database, send_closure(G()->background_manager(), &BackgroundManager::on_load_background_from_database,
std::move(slug), std::move(value)); std::move(slug), std::move(value));
})); }));
@ -563,7 +563,7 @@ void BackgroundManager::on_load_background_from_database(string name, string val
} else { } else {
if (background.name != name) { if (background.name != name) {
LOG(ERROR) << "Expected background " << name << ", but received " << background.name; LOG(ERROR) << "Expected background " << name << ", but received " << background.name;
name_to_background_id_.emplace(name, background.id); name_to_background_id_.emplace(std::move(name), background.id);
} }
add_background(background, false); add_background(background, false);
} }

View File

@ -38,8 +38,8 @@ class BackgroundManager final : public Actor {
void get_backgrounds(bool for_dark_theme, Promise<td_api::object_ptr<td_api::backgrounds>> &&promise); void get_backgrounds(bool for_dark_theme, Promise<td_api::object_ptr<td_api::backgrounds>> &&promise);
Result<string> get_background_url(const string &name, static Result<string> get_background_url(const string &name,
td_api::object_ptr<td_api::BackgroundType> background_type) const; td_api::object_ptr<td_api::BackgroundType> background_type);
void reload_background(BackgroundId background_id, int64 access_hash, Promise<Unit> &&promise); void reload_background(BackgroundId background_id, int64 access_hash, Promise<Unit> &&promise);

View File

@ -222,7 +222,7 @@ bool BackgroundFill::is_dark() const {
(fourth_color_ == -1 || (fourth_color_ & 0x808080) == 0); (fourth_color_ == -1 || (fourth_color_ & 0x808080) == 0);
default: default:
UNREACHABLE(); UNREACHABLE();
return 0; return false;
} }
} }

View File

@ -457,7 +457,7 @@ void CallActor::on_begin_exchanging_key() {
call_state_.type = CallState::Type::ExchangingKey; call_state_.type = CallState::Type::ExchangingKey;
call_state_need_flush_ = true; call_state_need_flush_ = true;
int64 call_receive_timeout_ms = G()->shared_config().get_option_integer("call_receive_timeout_ms", 20000); int64 call_receive_timeout_ms = G()->shared_config().get_option_integer("call_receive_timeout_ms", 20000);
double timeout = static_cast<double>(call_receive_timeout_ms) * 0.001; auto timeout = static_cast<double>(call_receive_timeout_ms) * 0.001;
LOG(INFO) << "Set call timeout to " << timeout; LOG(INFO) << "Set call timeout to " << timeout;
set_timeout_in(timeout); set_timeout_in(timeout);
} }
@ -484,7 +484,7 @@ Status CallActor::do_update_call(telegram_api::phoneCall &call) {
get_emojis_fingerprint(call_state_.key, is_outgoing_ ? dh_handshake_.get_g_b() : dh_handshake_.get_g_a()); get_emojis_fingerprint(call_state_.key, is_outgoing_ ? dh_handshake_.get_g_b() : dh_handshake_.get_g_a());
for (auto &connection : call.connections_) { for (auto &connection : call.connections_) {
call_state_.connections.push_back(CallConnection(*connection)); call_state_.connections.emplace_back(*connection);
} }
call_state_.protocol = CallProtocol(*call.protocol_); call_state_.protocol = CallProtocol(*call.protocol_);
call_state_.allow_p2p = (call.flags_ & telegram_api::phoneCall::P2P_ALLOWED_MASK) != 0; call_state_.allow_p2p = (call.flags_ & telegram_api::phoneCall::P2P_ALLOWED_MASK) != 0;
@ -636,7 +636,7 @@ void CallActor::try_send_request_query() {
auto query = G()->net_query_creator().create(tl_query); auto query = G()->net_query_creator().create(tl_query);
state_ = State::WaitRequestResult; state_ = State::WaitRequestResult;
int64 call_receive_timeout_ms = G()->shared_config().get_option_integer("call_receive_timeout_ms", 20000); int64 call_receive_timeout_ms = G()->shared_config().get_option_integer("call_receive_timeout_ms", 20000);
double timeout = static_cast<double>(call_receive_timeout_ms) * 0.001; auto timeout = static_cast<double>(call_receive_timeout_ms) * 0.001;
LOG(INFO) << "Set call timeout to " << timeout; LOG(INFO) << "Set call timeout to " << timeout;
set_timeout_in(timeout); set_timeout_in(timeout);
query->total_timeout_limit_ = max(timeout, 10.0); query->total_timeout_limit_ = max(timeout, 10.0);

View File

@ -70,7 +70,7 @@ struct CallState {
enum class Type : int32 { Empty, Pending, ExchangingKey, Ready, HangingUp, Discarded, Error } type{Type::Empty}; enum class Type : int32 { Empty, Pending, ExchangingKey, Ready, HangingUp, Discarded, Error } type{Type::Empty};
CallProtocol protocol; CallProtocol protocol;
std::vector<CallConnection> connections; vector<CallConnection> connections;
CallDiscardReason discard_reason{CallDiscardReason::Empty}; CallDiscardReason discard_reason{CallDiscardReason::Empty};
bool is_created{false}; bool is_created{false};
bool is_received{false}; bool is_received{false};

View File

@ -79,7 +79,9 @@ class GetBotCallbackAnswerQuery final : public Td::ResultHandler {
return on_error(id, result_ptr.move_as_error()); return on_error(id, result_ptr.move_as_error());
} }
td->callback_queries_manager_->on_get_callback_query_answer(result_ptr.move_as_ok(), std::move(promise_)); auto answer = result_ptr.move_as_ok();
bool show_alert = (answer->flags_ & telegram_api::messages_botCallbackAnswer::ALERT_MASK) != 0;
promise_.set_value(td_api::make_object<td_api::callbackQueryAnswer>(answer->message_, show_alert, answer->url_));
} }
void on_error(uint64 id, Status status) final { void on_error(uint64 id, Status status) final {
@ -288,12 +290,4 @@ void CallbackQueriesManager::send_get_callback_answer_query(
->send(dialog_id, full_message_id.get_message_id(), payload, std::move(password)); ->send(dialog_id, full_message_id.get_message_id(), payload, std::move(password));
} }
void CallbackQueriesManager::on_get_callback_query_answer(
tl_object_ptr<telegram_api::messages_botCallbackAnswer> &&answer,
Promise<td_api::object_ptr<td_api::callbackQueryAnswer>> &&promise) {
CHECK(answer != nullptr);
bool show_alert = (answer->flags_ & BOT_CALLBACK_ANSWER_FLAG_NEED_SHOW_ALERT) != 0;
promise.set_value(td_api::make_object<td_api::callbackQueryAnswer>(answer->message_, show_alert, answer->url_));
}
} // namespace td } // namespace td

View File

@ -42,16 +42,13 @@ class CallbackQueriesManager {
void send_callback_query(FullMessageId full_message_id, tl_object_ptr<td_api::CallbackQueryPayload> &&payload, void send_callback_query(FullMessageId full_message_id, tl_object_ptr<td_api::CallbackQueryPayload> &&payload,
Promise<td_api::object_ptr<td_api::callbackQueryAnswer>> &&promise); Promise<td_api::object_ptr<td_api::callbackQueryAnswer>> &&promise);
void on_get_callback_query_answer(tl_object_ptr<telegram_api::messages_botCallbackAnswer> &&answer,
Promise<td_api::object_ptr<td_api::callbackQueryAnswer>> &&promise);
private: private:
static constexpr int32 BOT_CALLBACK_ANSWER_FLAG_HAS_MESSAGE = 1 << 0; static constexpr int32 BOT_CALLBACK_ANSWER_FLAG_HAS_MESSAGE = 1 << 0;
static constexpr int32 BOT_CALLBACK_ANSWER_FLAG_NEED_SHOW_ALERT = 1 << 1; static constexpr int32 BOT_CALLBACK_ANSWER_FLAG_NEED_SHOW_ALERT = 1 << 1;
static constexpr int32 BOT_CALLBACK_ANSWER_FLAG_HAS_URL = 1 << 2; static constexpr int32 BOT_CALLBACK_ANSWER_FLAG_HAS_URL = 1 << 2;
tl_object_ptr<td_api::CallbackQueryPayload> get_query_payload(int32 flags, BufferSlice &&data, static tl_object_ptr<td_api::CallbackQueryPayload> get_query_payload(int32 flags, BufferSlice &&data,
string &&game_short_name); string &&game_short_name);
void send_get_callback_answer_query(FullMessageId full_message_id, void send_get_callback_answer_query(FullMessageId full_message_id,
tl_object_ptr<td_api::CallbackQueryPayload> &&payload, tl_object_ptr<td_api::CallbackQueryPayload> &&payload,

View File

@ -640,9 +640,9 @@ Client::Response Client::execute(Request &&request) {
return response; return response;
} }
Client::Client(Client &&other) noexcept = default;
Client &Client::operator=(Client &&other) noexcept = default;
Client::~Client() = default; Client::~Client() = default;
Client::Client(Client &&other) = default;
Client &Client::operator=(Client &&other) = default;
ClientManager::ClientManager() : impl_(std::make_unique<Impl>()) { ClientManager::ClientManager() : impl_(std::make_unique<Impl>()) {
} }
@ -682,9 +682,9 @@ void ClientManager::set_log_message_callback(int max_verbosity_level, LogMessage
} }
} }
ClientManager::ClientManager(ClientManager &&other) noexcept = default;
ClientManager &ClientManager::operator=(ClientManager &&other) noexcept = default;
ClientManager::~ClientManager() = default; ClientManager::~ClientManager() = default;
ClientManager::ClientManager(ClientManager &&other) = default;
ClientManager &ClientManager::operator=(ClientManager &&other) = default;
ClientManager *ClientManager::get_manager_singleton() { ClientManager *ClientManager::get_manager_singleton() {
static ClientManager client_manager; static ClientManager client_manager;

View File

@ -119,12 +119,12 @@ class Client final {
/** /**
* Move constructor. * Move constructor.
*/ */
Client(Client &&other); Client(Client &&other) noexcept;
/** /**
* Move assignment operator. * Move assignment operator.
*/ */
Client &operator=(Client &&other); Client &operator=(Client &&other) noexcept;
private: private:
class Impl; class Impl;
@ -267,12 +267,12 @@ class ClientManager final {
/** /**
* Move constructor. * Move constructor.
*/ */
ClientManager(ClientManager &&other); ClientManager(ClientManager &&other) noexcept;
/** /**
* Move assignment operator. * Move assignment operator.
*/ */
ClientManager &operator=(ClientManager &&other); ClientManager &operator=(ClientManager &&other) noexcept;
/** /**
* Returns a pointer to a singleton ClientManager instance. * Returns a pointer to a singleton ClientManager instance.

View File

@ -26,9 +26,9 @@ void ClientActor::request(uint64 id, td_api::object_ptr<td_api::Function> reques
ClientActor::~ClientActor() = default; ClientActor::~ClientActor() = default;
ClientActor::ClientActor(ClientActor &&other) = default; ClientActor::ClientActor(ClientActor &&other) noexcept = default;
ClientActor &ClientActor::operator=(ClientActor &&other) = default; ClientActor &ClientActor::operator=(ClientActor &&other) noexcept = default;
td_api::object_ptr<td_api::Object> ClientActor::execute(td_api::object_ptr<td_api::Function> request) { td_api::object_ptr<td_api::Object> ClientActor::execute(td_api::object_ptr<td_api::Function> request) {
return Td::static_request(std::move(request)); return Td::static_request(std::move(request));

View File

@ -64,19 +64,20 @@ class ClientActor final : public Actor {
/** /**
* Destroys the ClientActor and the TDLib instance. * Destroys the ClientActor and the TDLib instance.
*/ */
~ClientActor(); ~ClientActor() final;
/** /**
* Move constructor. * Move constructor.
*/ */
ClientActor(ClientActor &&other); ClientActor(ClientActor &&other) noexcept;
/** /**
* Move assignment operator. * Move assignment operator.
*/ */
ClientActor &operator=(ClientActor &&other); ClientActor &operator=(ClientActor &&other) noexcept;
ClientActor(const ClientActor &other) = delete; ClientActor(const ClientActor &other) = delete;
ClientActor &operator=(const ClientActor &other) = delete; ClientActor &operator=(const ClientActor &other) = delete;
private: private:

View File

@ -379,7 +379,8 @@ ActorOwn<> get_simple_config_firebase_firestore(Promise<SimpleConfigResult> prom
prefer_ipv6, std::move(get_config)); prefer_ipv6, std::move(get_config));
} }
ActorOwn<> get_full_config(DcOption option, Promise<FullConfig> promise, ActorShared<> parent) { static ActorOwn<> get_full_config(DcOption option, Promise<tl_object_ptr<telegram_api::config>> promise,
ActorShared<> parent) {
class SessionCallback final : public Session::Callback { class SessionCallback final : public Session::Callback {
public: public:
SessionCallback(ActorShared<> parent, DcOption option) : parent_(std::move(parent)), option_(std::move(option)) { SessionCallback(ActorShared<> parent, DcOption option) : parent_(std::move(parent)), option_(std::move(option)) {
@ -496,7 +497,7 @@ ActorOwn<> get_full_config(DcOption option, Promise<FullConfig> promise, ActorSh
class GetConfigActor final : public NetQueryCallback { class GetConfigActor final : public NetQueryCallback {
public: public:
GetConfigActor(DcOption option, Promise<FullConfig> promise, ActorShared<> parent) GetConfigActor(DcOption option, Promise<tl_object_ptr<telegram_api::config>> promise, ActorShared<> parent)
: option_(std::move(option)), promise_(std::move(promise)), parent_(std::move(parent)) { : option_(std::move(option)), promise_(std::move(promise)), parent_(std::move(parent)) {
} }
@ -542,11 +543,12 @@ ActorOwn<> get_full_config(DcOption option, Promise<FullConfig> promise, ActorSh
DcOption option_; DcOption option_;
ActorOwn<Session> session_; ActorOwn<Session> session_;
Promise<FullConfig> promise_; Promise<tl_object_ptr<telegram_api::config>> promise_;
ActorShared<> parent_; ActorShared<> parent_;
}; };
return ActorOwn<>(create_actor<GetConfigActor>("GetConfigActor", option, std::move(promise), std::move(parent))); return ActorOwn<>(
create_actor<GetConfigActor>("GetConfigActor", std::move(option), std::move(promise), std::move(parent)));
} }
class ConfigRecoverer final : public Actor { class ConfigRecoverer final : public Actor {
@ -556,7 +558,7 @@ class ConfigRecoverer final : public Actor {
} }
void on_dc_options_update(DcOptions dc_options) { void on_dc_options_update(DcOptions dc_options) {
dc_options_update_ = dc_options; dc_options_update_ = std::move(dc_options);
update_dc_options(); update_dc_options();
loop(); loop();
} }
@ -676,22 +678,22 @@ class ConfigRecoverer final : public Actor {
} }
} }
void on_full_config(Result<FullConfig> r_full_config, bool dummy) { void on_full_config(Result<tl_object_ptr<telegram_api::config>> r_full_config, bool dummy) {
full_config_query_.reset(); full_config_query_.reset();
if (r_full_config.is_ok()) { if (r_full_config.is_ok()) {
full_config_ = r_full_config.move_as_ok(); full_config_ = r_full_config.move_as_ok();
VLOG(config_recoverer) << "Got FullConfig " << to_string(full_config_); VLOG(config_recoverer) << "Receive " << to_string(full_config_);
full_config_expires_at_ = get_config_expire_time(); full_config_expires_at_ = get_config_expire_time();
send_closure(G()->connection_creator(), &ConnectionCreator::on_dc_options, DcOptions(full_config_->dc_options_)); send_closure(G()->connection_creator(), &ConnectionCreator::on_dc_options, DcOptions(full_config_->dc_options_));
} else { } else {
VLOG(config_recoverer) << "Get FullConfig error " << r_full_config.error(); VLOG(config_recoverer) << "Failed to get config: " << r_full_config.error();
full_config_ = FullConfig(); full_config_ = nullptr;
full_config_expires_at_ = get_failed_config_expire_time(); full_config_expires_at_ = get_failed_config_expire_time();
} }
loop(); loop();
} }
bool expect_blocking() const { static bool expect_blocking() {
return G()->shared_config().get_option_boolean("expect_blocking", true); return G()->shared_config().get_option_boolean("expect_blocking", true);
} }
@ -729,7 +731,7 @@ class ConfigRecoverer final : public Actor {
size_t date_option_i_{0}; size_t date_option_i_{0};
FullConfig full_config_; tl_object_ptr<telegram_api::config> full_config_;
double full_config_expires_at_{0}; double full_config_expires_at_{0};
ActorOwn<> full_config_query_; ActorOwn<> full_config_query_;
@ -760,6 +762,7 @@ class ConfigRecoverer final : public Actor {
double max_connecting_delay() const { double max_connecting_delay() const {
return expect_blocking() ? 5 : 20; return expect_blocking() ? 5 : 20;
} }
void loop() final { void loop() final {
if (close_flag_) { if (close_flag_) {
return; return;
@ -829,12 +832,13 @@ class ConfigRecoverer final : public Actor {
if (need_full_config) { if (need_full_config) {
ref_cnt_++; ref_cnt_++;
VLOG(config_recoverer) << "Ask full config with dc_options_i_ = " << dc_options_i_; VLOG(config_recoverer) << "Ask full config with dc_options_i_ = " << dc_options_i_;
full_config_query_ = full_config_query_ = get_full_config(
get_full_config(dc_options_.dc_options[dc_options_i_], dc_options_.dc_options[dc_options_i_],
PromiseCreator::lambda([actor_id = actor_id(this)](Result<FullConfig> r_full_config) { PromiseCreator::lambda(
send_closure(actor_id, &ConfigRecoverer::on_full_config, std::move(r_full_config), false); [actor_id = actor_id(this)](Result<tl_object_ptr<telegram_api::config>> r_full_config) {
}), send_closure(actor_id, &ConfigRecoverer::on_full_config, std::move(r_full_config), false);
actor_shared(this)); }),
actor_shared(this));
dc_options_i_ = (dc_options_i_ + 1) % dc_options_.dc_options.size(); dc_options_i_ = (dc_options_i_ + 1) % dc_options_.dc_options.size();
} }
@ -1041,13 +1045,12 @@ void ConfigManager::set_archive_and_mute(bool archive_and_mute, Promise<Unit> &&
void ConfigManager::on_dc_options_update(DcOptions dc_options) { void ConfigManager::on_dc_options_update(DcOptions dc_options) {
save_dc_options_update(dc_options); save_dc_options_update(dc_options);
send_closure(config_recoverer_, &ConfigRecoverer::on_dc_options_update, std::move(dc_options)); if (!dc_options.dc_options.empty()) {
if (dc_options.dc_options.empty()) { expire_time_ = Timestamp::now();
return; save_config_expire(expire_time_);
set_timeout_in(expire_time_.in());
} }
expire_time_ = Timestamp::now(); send_closure(config_recoverer_, &ConfigRecoverer::on_dc_options_update, std::move(dc_options));
save_config_expire(expire_time_);
set_timeout_in(expire_time_.in());
} }
void ConfigManager::request_config_from_dc_impl(DcId dc_id) { void ConfigManager::request_config_from_dc_impl(DcId dc_id) {
@ -1283,7 +1286,7 @@ void ConfigManager::on_result(NetQueryPtr res) {
} }
} }
void ConfigManager::save_dc_options_update(DcOptions dc_options) { void ConfigManager::save_dc_options_update(const DcOptions &dc_options) {
if (dc_options.dc_options.empty()) { if (dc_options.dc_options.empty()) {
G()->td_db()->get_binlog_pmc()->erase("dc_options_update"); G()->td_db()->get_binlog_pmc()->erase("dc_options_update");
return; return;

View File

@ -78,10 +78,6 @@ class HttpDate {
static Result<int32> parse_http_date(std::string slice); static Result<int32> parse_http_date(std::string slice);
}; };
using FullConfig = tl_object_ptr<telegram_api::config>;
ActorOwn<> get_full_config(DcId dc_id, IPAddress ip_address, Promise<FullConfig> promise);
class ConfigRecoverer; class ConfigRecoverer;
class ConfigManager final : public NetQueryCallback { class ConfigManager final : public NetQueryCallback {
public: public:
@ -155,7 +151,7 @@ class ConfigManager final : public NetQueryCallback {
static Timestamp load_config_expire_time(); static Timestamp load_config_expire_time();
static void save_config_expire(Timestamp timestamp); static void save_config_expire(Timestamp timestamp);
static void save_dc_options_update(DcOptions dc_options); static void save_dc_options_update(const DcOptions &dc_options);
static DcOptions load_dc_options_update(); static DcOptions load_dc_options_update();
ActorShared<> create_reference(); ActorShared<> create_reference();

View File

@ -23,7 +23,7 @@ void ConfigShared::set_callback(unique_ptr<Callback> callback) {
return; return;
} }
for (auto key_value : config_pmc_->get_all()) { for (const auto &key_value : config_pmc_->get_all()) {
on_option_updated(key_value.first); on_option_updated(key_value.first);
} }
} }

View File

@ -581,7 +581,7 @@ class ImportContactsQuery final : public Td::ResultHandler {
return promise_.set_error(Status::Error(429, "Too Many Requests: retry after 3600")); return promise_.set_error(Status::Error(429, "Too Many Requests: retry after 3600"));
} }
int64 total_size = static_cast<int64>(input_contacts_.size()); auto total_size = static_cast<int64>(input_contacts_.size());
vector<tl_object_ptr<telegram_api::inputPhoneContact>> contacts; vector<tl_object_ptr<telegram_api::inputPhoneContact>> contacts;
contacts.reserve(ptr->retry_contacts_.size()); contacts.reserve(ptr->retry_contacts_.size());
for (auto &client_id : ptr->retry_contacts_) { for (auto &client_id : ptr->retry_contacts_) {
@ -589,7 +589,7 @@ class ImportContactsQuery final : public Td::ResultHandler {
LOG(ERROR) << "Wrong client_id " << client_id << " returned"; LOG(ERROR) << "Wrong client_id " << client_id << " returned";
continue; continue;
} }
size_t i = static_cast<size_t>(client_id); auto i = static_cast<size_t>(client_id);
contacts.push_back(input_contacts_[i].get_input_phone_contact(client_id)); contacts.push_back(input_contacts_[i].get_input_phone_contact(client_id));
} }
@ -2272,7 +2272,8 @@ class EditChannelAdminQuery final : public Td::ResultHandler {
explicit EditChannelAdminQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) { explicit EditChannelAdminQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) {
} }
void send(ChannelId channel_id, tl_object_ptr<telegram_api::InputUser> &&input_user, DialogParticipantStatus status) { void send(ChannelId channel_id, tl_object_ptr<telegram_api::InputUser> &&input_user,
const DialogParticipantStatus &status) {
channel_id_ = channel_id; channel_id_ = channel_id;
auto input_channel = td->contacts_manager_->get_input_channel(channel_id); auto input_channel = td->contacts_manager_->get_input_channel(channel_id);
CHECK(input_channel != nullptr); CHECK(input_channel != nullptr);
@ -2307,7 +2308,8 @@ class EditChannelBannedQuery final : public Td::ResultHandler {
explicit EditChannelBannedQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) { explicit EditChannelBannedQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) {
} }
void send(ChannelId channel_id, tl_object_ptr<telegram_api::InputPeer> &&input_peer, DialogParticipantStatus status) { void send(ChannelId channel_id, tl_object_ptr<telegram_api::InputPeer> &&input_peer,
const DialogParticipantStatus &status) {
channel_id_ = channel_id; channel_id_ = channel_id;
auto input_channel = td->contacts_manager_->get_input_channel(channel_id); auto input_channel = td->contacts_manager_->get_input_channel(channel_id);
CHECK(input_channel != nullptr); CHECK(input_channel != nullptr);
@ -2686,7 +2688,7 @@ class GetUserPhotosQuery final : public Td::ResultHandler {
auto photos = move_tl_object_as<telegram_api::photos_photos>(ptr); auto photos = move_tl_object_as<telegram_api::photos_photos>(ptr);
td->contacts_manager_->on_get_users(std::move(photos->users_), "GetUserPhotosQuery"); td->contacts_manager_->on_get_users(std::move(photos->users_), "GetUserPhotosQuery");
int32 photos_size = narrow_cast<int32>(photos->photos_.size()); auto photos_size = narrow_cast<int32>(photos->photos_.size());
td->contacts_manager_->on_get_user_photos(user_id_, offset_, limit_, photos_size, std::move(photos->photos_)); td->contacts_manager_->on_get_user_photos(user_id_, offset_, limit_, photos_size, std::move(photos->photos_));
} else { } else {
CHECK(constructor_id == telegram_api::photos_photosSlice::ID); CHECK(constructor_id == telegram_api::photos_photosSlice::ID);
@ -2925,7 +2927,7 @@ class GetChannelParticipantsQuery final : public Td::ResultHandler {
: promise_(std::move(promise)) { : promise_(std::move(promise)) {
} }
void send(ChannelId channel_id, ChannelParticipantsFilter filter, int32 offset, int32 limit) { void send(ChannelId channel_id, const ChannelParticipantsFilter &filter, int32 offset, int32 limit) {
auto input_channel = td->contacts_manager_->get_input_channel(channel_id); auto input_channel = td->contacts_manager_->get_input_channel(channel_id);
if (input_channel == nullptr) { if (input_channel == nullptr) {
return promise_.set_error(Status::Error(400, "Supergroup not found")); return promise_.set_error(Status::Error(400, "Supergroup not found"));
@ -5182,7 +5184,7 @@ td_api::object_ptr<td_api::session> ContactsManager::convert_authorization_objec
authorization->country_, authorization->region_); authorization->country_, authorization->region_);
} }
void ContactsManager::confirm_qr_code_authentication(string link, void ContactsManager::confirm_qr_code_authentication(const string &link,
Promise<td_api::object_ptr<td_api::session>> &&promise) { Promise<td_api::object_ptr<td_api::session>> &&promise) {
Slice prefix("tg://login?token="); Slice prefix("tg://login?token=");
if (!begins_with(to_lower(link), prefix)) { if (!begins_with(to_lower(link), prefix)) {
@ -5373,7 +5375,7 @@ std::pair<vector<UserId>, vector<int32>> ContactsManager::import_contacts(const
return {}; return {};
} }
void ContactsManager::remove_contacts(vector<UserId> user_ids, Promise<Unit> &&promise) { void ContactsManager::remove_contacts(const vector<UserId> &user_ids, Promise<Unit> &&promise) {
LOG(INFO) << "Delete contacts: " << format::as_array(user_ids); LOG(INFO) << "Delete contacts: " << format::as_array(user_ids);
if (!are_contacts_loaded_) { if (!are_contacts_loaded_) {
load_contacts(std::move(promise)); load_contacts(std::move(promise));
@ -5587,7 +5589,7 @@ std::pair<vector<UserId>, vector<int32>> ContactsManager::change_imported_contac
std::pair<vector<size_t>, vector<Contact>> to_add; std::pair<vector<size_t>, vector<Contact>> to_add;
for (auto &new_contact : different_new_contacts) { for (auto &new_contact : different_new_contacts) {
to_add.first.push_back(new_contact.second); to_add.first.push_back(new_contact.second);
to_add.second.push_back(std::move(new_contact.first)); to_add.second.push_back(new_contact.first);
} }
if (to_add.first.empty() && to_delete.empty()) { if (to_add.first.empty() && to_delete.empty()) {
@ -6671,16 +6673,16 @@ void ContactsManager::send_get_channel_message_stats_query(
->send(dialog_id.get_channel_id(), full_message_id.get_message_id(), is_dark, dc_id); ->send(dialog_id.get_channel_id(), full_message_id.get_message_id(), is_dark, dc_id);
} }
void ContactsManager::load_statistics_graph(DialogId dialog_id, const string &token, int64 x, void ContactsManager::load_statistics_graph(DialogId dialog_id, string token, int64 x,
Promise<td_api::object_ptr<td_api::StatisticalGraph>> &&promise) { Promise<td_api::object_ptr<td_api::StatisticalGraph>> &&promise) {
auto dc_id_promise = PromiseCreator::lambda( auto dc_id_promise = PromiseCreator::lambda([actor_id = actor_id(this), token = std::move(token), x,
[actor_id = actor_id(this), token, x, promise = std::move(promise)](Result<DcId> r_dc_id) mutable { promise = std::move(promise)](Result<DcId> r_dc_id) mutable {
if (r_dc_id.is_error()) { if (r_dc_id.is_error()) {
return promise.set_error(r_dc_id.move_as_error()); return promise.set_error(r_dc_id.move_as_error());
} }
send_closure(actor_id, &ContactsManager::send_load_async_graph_query, r_dc_id.move_as_ok(), std::move(token), x, send_closure(actor_id, &ContactsManager::send_load_async_graph_query, r_dc_id.move_as_ok(), std::move(token), x,
std::move(promise)); std::move(promise));
}); });
get_channel_statistics_dc_id(dialog_id, false, std::move(dc_id_promise)); get_channel_statistics_dc_id(dialog_id, false, std::move(dc_id_promise));
} }
@ -6811,8 +6813,8 @@ void ContactsManager::add_chat_participant(ChatId chat_id, UserId user_id, int32
td_->create_handler<AddChatUserQuery>(std::move(promise))->send(chat_id, std::move(input_user), forward_limit); td_->create_handler<AddChatUserQuery>(std::move(promise))->send(chat_id, std::move(input_user), forward_limit);
} }
void ContactsManager::add_channel_participant(ChannelId channel_id, UserId user_id, Promise<Unit> &&promise, void ContactsManager::add_channel_participant(ChannelId channel_id, UserId user_id,
DialogParticipantStatus old_status) { const DialogParticipantStatus &old_status, Promise<Unit> &&promise) {
if (td_->auth_manager_->is_bot()) { if (td_->auth_manager_->is_bot()) {
return promise.set_error(Status::Error(400, "Bots can't add new chat members")); return promise.set_error(Status::Error(400, "Bots can't add new chat members"));
} }
@ -6986,8 +6988,8 @@ void ContactsManager::set_channel_participant_status_impl(ChannelId channel_id,
if (participant_dialog_id.get_type() != DialogType::User) { if (participant_dialog_id.get_type() != DialogType::User) {
return promise.set_error(Status::Error(400, "Can't promote chats to chat administrators")); return promise.set_error(Status::Error(400, "Can't promote chats to chat administrators"));
} }
return promote_channel_participant(channel_id, participant_dialog_id.get_user_id(), std::move(status), return promote_channel_participant(channel_id, participant_dialog_id.get_user_id(), status, old_status,
std::move(old_status), std::move(promise)); std::move(promise));
} else if (need_restrict) { } else if (need_restrict) {
return restrict_channel_participant(channel_id, participant_dialog_id, std::move(status), std::move(old_status), return restrict_channel_participant(channel_id, participant_dialog_id, std::move(status), std::move(old_status),
std::move(promise)); std::move(promise));
@ -6996,13 +6998,13 @@ void ContactsManager::set_channel_participant_status_impl(ChannelId channel_id,
if (participant_dialog_id.get_type() != DialogType::User) { if (participant_dialog_id.get_type() != DialogType::User) {
return promise.set_error(Status::Error(400, "Can't add chats as chat members")); return promise.set_error(Status::Error(400, "Can't add chats as chat members"));
} }
return add_channel_participant(channel_id, participant_dialog_id.get_user_id(), std::move(promise), return add_channel_participant(channel_id, participant_dialog_id.get_user_id(), old_status, std::move(promise));
std::move(old_status));
} }
} }
void ContactsManager::promote_channel_participant(ChannelId channel_id, UserId user_id, DialogParticipantStatus status, void ContactsManager::promote_channel_participant(ChannelId channel_id, UserId user_id,
DialogParticipantStatus old_status, Promise<Unit> &&promise) { const DialogParticipantStatus &status,
const DialogParticipantStatus &old_status, Promise<Unit> &&promise) {
LOG(INFO) << "Promote " << user_id << " in " << channel_id << " from " << old_status << " to " << status; LOG(INFO) << "Promote " << user_id << " in " << channel_id << " from " << old_status << " to " << status;
const Channel *c = get_channel(channel_id); const Channel *c = get_channel(channel_id);
CHECK(c != nullptr); CHECK(c != nullptr);
@ -7459,8 +7461,8 @@ void ContactsManager::delete_chat_participant(ChatId chat_id, UserId user_id, bo
} }
void ContactsManager::restrict_channel_participant(ChannelId channel_id, DialogId participant_dialog_id, void ContactsManager::restrict_channel_participant(ChannelId channel_id, DialogId participant_dialog_id,
DialogParticipantStatus status, DialogParticipantStatus old_status, DialogParticipantStatus &&status,
Promise<Unit> &&promise) { DialogParticipantStatus &&old_status, Promise<Unit> &&promise) {
TRY_STATUS_PROMISE(promise, G()->close_status()); TRY_STATUS_PROMISE(promise, G()->close_status());
LOG(INFO) << "Restrict " << participant_dialog_id << " in " << channel_id << " from " << old_status << " to " LOG(INFO) << "Restrict " << participant_dialog_id << " in " << channel_id << " from " << old_status << " to "
@ -7521,22 +7523,23 @@ void ContactsManager::restrict_channel_participant(ChannelId channel_id, DialogI
if (old_status.is_member() && !status.is_member() && !status.is_banned()) { if (old_status.is_member() && !status.is_member() && !status.is_banned()) {
// we can't make participant Left without kicking it first // we can't make participant Left without kicking it first
auto on_result_promise = PromiseCreator::lambda([actor_id = actor_id(this), channel_id, participant_dialog_id, auto on_result_promise = PromiseCreator::lambda([actor_id = actor_id(this), channel_id, participant_dialog_id,
status, promise = std::move(promise)](Result<> result) mutable { status = std::move(status),
promise = std::move(promise)](Result<> result) mutable {
if (result.is_error()) { if (result.is_error()) {
return promise.set_error(result.move_as_error()); return promise.set_error(result.move_as_error());
} }
create_actor<SleepActor>("RestrictChannelParticipantSleepActor", 1.0, create_actor<SleepActor>(
PromiseCreator::lambda([actor_id, channel_id, participant_dialog_id, status, "RestrictChannelParticipantSleepActor", 1.0,
promise = std::move(promise)](Result<> result) mutable { PromiseCreator::lambda([actor_id, channel_id, participant_dialog_id, status = std::move(status),
if (result.is_error()) { promise = std::move(promise)](Result<> result) mutable {
return promise.set_error(result.move_as_error()); if (result.is_error()) {
} return promise.set_error(result.move_as_error());
}
send_closure(actor_id, &ContactsManager::restrict_channel_participant, channel_id, send_closure(actor_id, &ContactsManager::restrict_channel_participant, channel_id, participant_dialog_id,
participant_dialog_id, status, DialogParticipantStatus::Banned(0), std::move(status), DialogParticipantStatus::Banned(0), std::move(promise));
std::move(promise)); }))
}))
.release(); .release();
}); });
@ -7606,7 +7609,7 @@ vector<DialogId> ContactsManager::get_dialog_ids(vector<tl_object_ptr<telegram_a
} }
vector<DialogId> ContactsManager::get_created_public_dialogs(PublicDialogType type, Promise<Unit> &&promise) { vector<DialogId> ContactsManager::get_created_public_dialogs(PublicDialogType type, Promise<Unit> &&promise) {
int32 index = static_cast<int32>(type); auto index = static_cast<int32>(type);
if (created_public_channels_inited_[index]) { if (created_public_channels_inited_[index]) {
promise.set_value(Unit()); promise.set_value(Unit());
return transform(created_public_channels_[index], [&](ChannelId channel_id) { return transform(created_public_channels_[index], [&](ChannelId channel_id) {
@ -7622,7 +7625,7 @@ vector<DialogId> ContactsManager::get_created_public_dialogs(PublicDialogType ty
void ContactsManager::on_get_created_public_channels(PublicDialogType type, void ContactsManager::on_get_created_public_channels(PublicDialogType type,
vector<tl_object_ptr<telegram_api::Chat>> &&chats) { vector<tl_object_ptr<telegram_api::Chat>> &&chats) {
int32 index = static_cast<int32>(type); auto index = static_cast<int32>(type);
created_public_channels_[index] = get_channel_ids(std::move(chats), "on_get_created_public_channels"); created_public_channels_[index] = get_channel_ids(std::move(chats), "on_get_created_public_channels");
created_public_channels_inited_[index] = true; created_public_channels_inited_[index] = true;
} }
@ -9643,7 +9646,7 @@ ContactsManager::ChannelFull *ContactsManager::get_channel_full_force(ChannelId
return get_channel_full(channel_id, only_local, source); return get_channel_full(channel_id, only_local, source);
} }
void ContactsManager::for_each_secret_chat_with_user(UserId user_id, std::function<void(SecretChatId)> f) { void ContactsManager::for_each_secret_chat_with_user(UserId user_id, const std::function<void(SecretChatId)> &f) {
auto it = secret_chats_with_user_.find(user_id); auto it = secret_chats_with_user_.find(user_id);
if (it != secret_chats_with_user_.end()) { if (it != secret_chats_with_user_.end()) {
for (auto secret_chat_id : it->second) { for (auto secret_chat_id : it->second) {
@ -10225,7 +10228,7 @@ void ContactsManager::on_get_user_full(tl_object_ptr<telegram_api::userFull> &&u
void ContactsManager::on_get_user_photos(UserId user_id, int32 offset, int32 limit, int32 total_count, void ContactsManager::on_get_user_photos(UserId user_id, int32 offset, int32 limit, int32 total_count,
vector<tl_object_ptr<telegram_api::Photo>> photos) { vector<tl_object_ptr<telegram_api::Photo>> photos) {
int32 photo_count = narrow_cast<int32>(photos.size()); auto photo_count = narrow_cast<int32>(photos.size());
int32 min_total_count = (offset >= 0 && photo_count > 0 ? offset : 0) + photo_count; int32 min_total_count = (offset >= 0 && photo_count > 0 ? offset : 0) + photo_count;
if (total_count < min_total_count) { if (total_count < min_total_count) {
LOG(ERROR) << "Wrong photos total_count " << total_count << ". Receive " << photo_count << " photos with offset " LOG(ERROR) << "Wrong photos total_count " << total_count << ". Receive " << photo_count << " photos with offset "
@ -10754,7 +10757,7 @@ void ContactsManager::on_get_chat_full_failed(ChatId chat_id) {
return; return;
} }
LOG(INFO) << "Failed to get " << chat_id; LOG(INFO) << "Failed to get full " << chat_id;
} }
void ContactsManager::on_get_channel_full_failed(ChannelId channel_id) { void ContactsManager::on_get_channel_full_failed(ChannelId channel_id) {
@ -10762,7 +10765,7 @@ void ContactsManager::on_get_channel_full_failed(ChannelId channel_id) {
return; return;
} }
LOG(INFO) << "Failed to get " << channel_id; LOG(INFO) << "Failed to get full " << channel_id;
auto channel_full = get_channel_full(channel_id, true, "on_get_channel_full"); auto channel_full = get_channel_full(channel_id, true, "on_get_channel_full");
if (channel_full != nullptr) { if (channel_full != nullptr) {
channel_full->repair_request_version = 0; channel_full->repair_request_version = 0;
@ -10886,8 +10889,8 @@ void ContactsManager::do_update_user_photo(User *u, UserId user_id,
do_update_user_photo(u, user_id, std::move(new_photo), true, source); do_update_user_photo(u, user_id, std::move(new_photo), true, source);
} }
void ContactsManager::do_update_user_photo(User *u, UserId user_id, ProfilePhoto new_photo, bool invalidate_photo_cache, void ContactsManager::do_update_user_photo(User *u, UserId user_id, ProfilePhoto &&new_photo,
const char *source) { bool invalidate_photo_cache, const char *source) {
u->is_photo_inited = true; u->is_photo_inited = true;
if (new_photo != u->photo) { if (new_photo != u->photo) {
LOG_IF(ERROR, u->access_hash == -1 && new_photo.small_file_id.is_valid()) LOG_IF(ERROR, u->access_hash == -1 && new_photo.small_file_id.is_valid())
@ -11138,8 +11141,9 @@ void ContactsManager::on_update_user_full_common_chat_count(UserFull *user_full,
void ContactsManager::on_update_user_full_commands(UserFull *user_full, UserId user_id, void ContactsManager::on_update_user_full_commands(UserFull *user_full, UserId user_id,
vector<tl_object_ptr<telegram_api::botCommand>> &&bot_commands) { vector<tl_object_ptr<telegram_api::botCommand>> &&bot_commands) {
CHECK(user_full != nullptr); CHECK(user_full != nullptr);
auto commands = auto commands = transform(std::move(bot_commands), [](tl_object_ptr<telegram_api::botCommand> &&bot_command) {
transform(std::move(bot_commands), [](auto &&bot_command) { return BotCommand(std::move(bot_command)); }); return BotCommand(std::move(bot_command));
});
if (user_full->commands != commands) { if (user_full->commands != commands) {
user_full->commands = std::move(commands); user_full->commands = std::move(commands);
user_full->is_changed = true; user_full->is_changed = true;
@ -11164,7 +11168,7 @@ void ContactsManager::on_update_user_need_phone_number_privacy_exception(UserId
} }
void ContactsManager::on_update_user_full_need_phone_number_privacy_exception( void ContactsManager::on_update_user_full_need_phone_number_privacy_exception(
UserFull *user_full, UserId user_id, bool need_phone_number_privacy_exception) { UserFull *user_full, UserId user_id, bool need_phone_number_privacy_exception) const {
CHECK(user_full != nullptr); CHECK(user_full != nullptr);
if (need_phone_number_privacy_exception) { if (need_phone_number_privacy_exception) {
const User *u = get_user(user_id); const User *u = get_user(user_id);
@ -11238,6 +11242,7 @@ void ContactsManager::add_profile_photo_to_cache(UserId user_id, Photo &&photo)
if (user_photos->photos.empty() || user_photos->photos[0].id.get() != photo.id.get()) { if (user_photos->photos.empty() || user_photos->photos[0].id.get() != photo.id.get()) {
user_photos->photos.insert(user_photos->photos.begin(), photo); user_photos->photos.insert(user_photos->photos.begin(), photo);
user_photos->count++; user_photos->count++;
register_user_photo(u, user_id, user_photos->photos[0]);
} }
} else { } else {
user_photos->count++; user_photos->count++;
@ -11251,6 +11256,7 @@ void ContactsManager::add_profile_photo_to_cache(UserId user_id, Photo &&photo)
if (user_full->photo != photo) { if (user_full->photo != photo) {
user_full->photo = photo; user_full->photo = photo;
user_full->is_changed = true; user_full->is_changed = true;
register_user_photo(u, user_id, photo);
} }
update_user_full(user_full, user_id, "add_profile_photo_to_cache"); update_user_full(user_full, user_id, "add_profile_photo_to_cache");
} }
@ -11691,7 +11697,7 @@ void ContactsManager::on_get_channel_participants(
on_get_chats(std::move(channel_participants->chats_), "on_get_channel_participants"); on_get_chats(std::move(channel_participants->chats_), "on_get_channel_participants");
int32 total_count = channel_participants->count_; int32 total_count = channel_participants->count_;
auto participants = std::move(channel_participants->participants_); auto participants = std::move(channel_participants->participants_);
LOG(INFO) << "Receive " << participants.size() << " members in " << channel_id; LOG(INFO) << "Receive " << participants.size() << " " << filter << " members in " << channel_id;
bool is_full = offset == 0 && static_cast<int32>(participants.size()) < limit && total_count < limit; bool is_full = offset == 0 && static_cast<int32>(participants.size()) < limit && total_count < limit;
@ -11722,11 +11728,12 @@ void ContactsManager::on_get_channel_participants(
} }
if (total_count < narrow_cast<int32>(result.size())) { if (total_count < narrow_cast<int32>(result.size())) {
LOG(ERROR) << "Receive total_count = " << total_count << ", but have at least " << result.size() << " members in " LOG(ERROR) << "Receive total_count = " << total_count << ", but have at least " << result.size() << " " << filter
<< channel_id; << " members in " << channel_id;
total_count = static_cast<int32>(result.size()); total_count = static_cast<int32>(result.size());
} else if (is_full && total_count > static_cast<int32>(result.size())) { } else if (is_full && total_count > static_cast<int32>(result.size())) {
LOG(ERROR) << "Fix total number of members from " << total_count << " to " << result.size() << " in " << channel_id; LOG(ERROR) << "Fix total number of " << filter << " members from " << total_count << " to " << result.size()
<< " in " << channel_id;
total_count = static_cast<int32>(result.size()); total_count = static_cast<int32>(result.size());
} }
@ -12006,8 +12013,8 @@ void ContactsManager::speculative_add_channel_participant_count(ChannelId channe
} }
void ContactsManager::speculative_add_channel_user(ChannelId channel_id, UserId user_id, void ContactsManager::speculative_add_channel_user(ChannelId channel_id, UserId user_id,
DialogParticipantStatus new_status, const DialogParticipantStatus &new_status,
DialogParticipantStatus old_status) { const DialogParticipantStatus &old_status) {
auto c = get_channel_force(channel_id); auto c = get_channel_force(channel_id);
// channel full must be loaded before c->participant_count is updated, because on_load_channel_full_from_database // channel full must be loaded before c->participant_count is updated, because on_load_channel_full_from_database
// must copy the initial c->participant_count before it is speculatibely updated // must copy the initial c->participant_count before it is speculatibely updated
@ -12176,7 +12183,7 @@ void ContactsManager::on_update_chat_full_photo(ChatFull *chat_full, ChatId chat
drop_chat_photos(chat_id, true, false, "on_update_chat_full_photo"); drop_chat_photos(chat_id, true, false, "on_update_chat_full_photo");
} }
auto photo_file_ids = photo_get_file_ids(photo); auto photo_file_ids = photo_get_file_ids(chat_full->photo);
if (chat_full->registered_photo_file_ids == photo_file_ids) { if (chat_full->registered_photo_file_ids == photo_file_ids) {
return; return;
} }
@ -12213,7 +12220,7 @@ void ContactsManager::on_update_channel_full_photo(ChannelFull *channel_full, Ch
drop_channel_photos(channel_id, true, false, "on_update_channel_full_photo"); drop_channel_photos(channel_id, true, false, "on_update_channel_full_photo");
} }
auto photo_file_ids = photo_get_file_ids(photo); auto photo_file_ids = photo_get_file_ids(channel_full->photo);
if (channel_full->registered_photo_file_ids == photo_file_ids) { if (channel_full->registered_photo_file_ids == photo_file_ids) {
return; return;
} }
@ -12812,7 +12819,7 @@ void ContactsManager::on_update_chat_status(Chat *c, ChatId chat_id, DialogParti
bool need_reload_group_call = c->status.can_manage_calls() != status.can_manage_calls(); bool need_reload_group_call = c->status.can_manage_calls() != status.can_manage_calls();
bool need_drop_invite_link = c->status.can_manage_invite_links() && !status.can_manage_invite_links(); bool need_drop_invite_link = c->status.can_manage_invite_links() && !status.can_manage_invite_links();
c->status = status; c->status = std::move(status);
if (c->status.is_left()) { if (c->status.is_left()) {
c->participant_count = 0; c->participant_count = 0;
@ -13389,7 +13396,7 @@ void ContactsManager::on_update_channel_default_permissions(ChannelId channel_id
} }
void ContactsManager::send_update_chat_member(DialogId dialog_id, UserId agent_user_id, int32 date, void ContactsManager::send_update_chat_member(DialogId dialog_id, UserId agent_user_id, int32 date,
DialogInviteLink invite_link, const DialogInviteLink &invite_link,
const DialogParticipant &old_dialog_participant, const DialogParticipant &old_dialog_participant,
const DialogParticipant &new_dialog_participant) { const DialogParticipant &new_dialog_participant) {
CHECK(td_->auth_manager_->is_bot()); CHECK(td_->auth_manager_->is_bot());
@ -14634,8 +14641,8 @@ void ContactsManager::add_dialog_participant(DialogId dialog_id, UserId user_id,
case DialogType::Chat: case DialogType::Chat:
return add_chat_participant(dialog_id.get_chat_id(), user_id, forward_limit, std::move(promise)); return add_chat_participant(dialog_id.get_chat_id(), user_id, forward_limit, std::move(promise));
case DialogType::Channel: case DialogType::Channel:
return add_channel_participant(dialog_id.get_channel_id(), user_id, std::move(promise), return add_channel_participant(dialog_id.get_channel_id(), user_id, DialogParticipantStatus::Left(),
DialogParticipantStatus::Left()); std::move(promise));
case DialogType::SecretChat: case DialogType::SecretChat:
return promise.set_error(Status::Error(400, "Can't add members to a secret chat")); return promise.set_error(Status::Error(400, "Can't add members to a secret chat"));
case DialogType::None: case DialogType::None:
@ -15104,7 +15111,7 @@ void ContactsManager::get_channel_participants(ChannelId channel_id,
} }
}); });
td_->create_handler<GetChannelParticipantsQuery>(std::move(get_channel_participants_promise)) td_->create_handler<GetChannelParticipantsQuery>(std::move(get_channel_participants_promise))
->send(channel_id, std::move(participants_filter), offset, limit); ->send(channel_id, participants_filter, offset, limit);
} }
vector<DialogAdministrator> ContactsManager::get_dialog_administrators(DialogId dialog_id, int left_tries, vector<DialogAdministrator> ContactsManager::get_dialog_administrators(DialogId dialog_id, int left_tries,
@ -15163,12 +15170,13 @@ string ContactsManager::get_dialog_administrators_database_key(DialogId dialog_i
void ContactsManager::load_dialog_administrators(DialogId dialog_id, Promise<Unit> &&promise) { void ContactsManager::load_dialog_administrators(DialogId dialog_id, Promise<Unit> &&promise) {
if (G()->parameters().use_chat_info_db) { if (G()->parameters().use_chat_info_db) {
LOG(INFO) << "Load administrators of " << dialog_id << " from database"; LOG(INFO) << "Load administrators of " << dialog_id << " from database";
G()->td_db()->get_sqlite_pmc()->get( G()->td_db()->get_sqlite_pmc()->get(get_dialog_administrators_database_key(dialog_id),
get_dialog_administrators_database_key(dialog_id), PromiseCreator::lambda([actor_id = actor_id(this), dialog_id,
PromiseCreator::lambda([dialog_id, promise = std::move(promise)](string value) mutable { promise = std::move(promise)](string value) mutable {
send_closure(G()->contacts_manager(), &ContactsManager::on_load_dialog_administrators_from_database, send_closure(actor_id,
dialog_id, std::move(value), std::move(promise)); &ContactsManager::on_load_dialog_administrators_from_database,
})); dialog_id, std::move(value), std::move(promise));
}));
} else { } else {
promise.set_value(Unit()); promise.set_value(Unit());
} }
@ -15663,7 +15671,7 @@ void ContactsManager::on_chat_update(telegram_api::channelForbidden &channel, co
on_update_channel_status(c, channel_id, DialogParticipantStatus::Banned(unban_date)); on_update_channel_status(c, channel_id, DialogParticipantStatus::Banned(unban_date));
// on_update_channel_username(c, channel_id, ""); // don't know if channel username is empty, so don't update it // on_update_channel_username(c, channel_id, ""); // don't know if channel username is empty, so don't update it
tl_object_ptr<telegram_api::chatBannedRights> banned_rights; // == nullptr tl_object_ptr<telegram_api::chatBannedRights> banned_rights; // == nullptr
on_update_channel_default_permissions(c, channel_id, get_restricted_rights(banned_rights)); on_update_channel_default_permissions(c, channel_id, get_restricted_rights(std::move(banned_rights)));
td_->messages_manager_->on_update_dialog_group_call(DialogId(channel_id), false, false, "receive channelForbidden"); td_->messages_manager_->on_update_dialog_group_call(DialogId(channel_id), false, false, "receive channelForbidden");
bool sign_messages = false; bool sign_messages = false;
@ -15982,7 +15990,7 @@ tl_object_ptr<td_api::supergroup> ContactsManager::get_supergroup_object(Channel
return get_supergroup_object(channel_id, get_channel(channel_id)); return get_supergroup_object(channel_id, get_channel(channel_id));
} }
tl_object_ptr<td_api::supergroup> ContactsManager::get_supergroup_object(ChannelId channel_id, const Channel *c) const { tl_object_ptr<td_api::supergroup> ContactsManager::get_supergroup_object(ChannelId channel_id, const Channel *c) {
if (c == nullptr) { if (c == nullptr) {
return nullptr; return nullptr;
} }

View File

@ -113,7 +113,7 @@ class ContactsManager final : public Actor {
bool is_update_about_username_change_received(UserId user_id) const; bool is_update_about_username_change_received(UserId user_id) const;
void for_each_secret_chat_with_user(UserId user_id, std::function<void(SecretChatId)> f); void for_each_secret_chat_with_user(UserId user_id, const std::function<void(SecretChatId)> &f);
string get_user_username(UserId user_id) const; string get_user_username(UserId user_id) const;
string get_channel_username(ChannelId channel_id) const; string get_channel_username(ChannelId channel_id) const;
@ -280,14 +280,14 @@ class ContactsManager final : public Actor {
static td_api::object_ptr<td_api::session> convert_authorization_object( static td_api::object_ptr<td_api::session> convert_authorization_object(
tl_object_ptr<telegram_api::authorization> &&authorization); tl_object_ptr<telegram_api::authorization> &&authorization);
void confirm_qr_code_authentication(string link, Promise<td_api::object_ptr<td_api::session>> &&promise); void confirm_qr_code_authentication(const string &link, Promise<td_api::object_ptr<td_api::session>> &&promise);
void get_active_sessions(Promise<tl_object_ptr<td_api::sessions>> &&promise) const; void get_active_sessions(Promise<tl_object_ptr<td_api::sessions>> &&promise) const;
void terminate_session(int64 session_id, Promise<Unit> &&promise) const; void terminate_session(int64 session_id, Promise<Unit> &&promise) const;
void terminate_all_other_sessions(Promise<Unit> &&promise) const; void terminate_all_other_sessions(Promise<Unit> &&promise) const;
void get_connected_websites(Promise<tl_object_ptr<td_api::connectedWebsites>> &&promise) const; void get_connected_websites(Promise<tl_object_ptr<td_api::connectedWebsites>> &&promise) const;
void disconnect_website(int64 authorizations_id, Promise<Unit> &&promise) const; void disconnect_website(int64 website_id, Promise<Unit> &&promise) const;
void disconnect_all_websites(Promise<Unit> &&promise) const; void disconnect_all_websites(Promise<Unit> &&promise) const;
void add_contact(Contact contact, bool share_phone_number, Promise<Unit> &&promise); void add_contact(Contact contact, bool share_phone_number, Promise<Unit> &&promise);
@ -297,7 +297,7 @@ class ContactsManager final : public Actor {
std::pair<int32, vector<UserId>> search_contacts(const string &query, int32 limit, Promise<Unit> &&promise); std::pair<int32, vector<UserId>> search_contacts(const string &query, int32 limit, Promise<Unit> &&promise);
void remove_contacts(vector<UserId> user_ids, Promise<Unit> &&promise); void remove_contacts(const vector<UserId> &user_ids, Promise<Unit> &&promise);
void remove_contacts_by_phone_number(vector<string> user_phone_numbers, vector<UserId> user_ids, void remove_contacts_by_phone_number(vector<string> user_phone_numbers, vector<UserId> user_ids,
Promise<Unit> &&promise); Promise<Unit> &&promise);
@ -369,7 +369,7 @@ class ContactsManager final : public Actor {
void get_channel_message_statistics(FullMessageId full_message_id, bool is_dark, void get_channel_message_statistics(FullMessageId full_message_id, bool is_dark,
Promise<td_api::object_ptr<td_api::messageStatistics>> &&promise); Promise<td_api::object_ptr<td_api::messageStatistics>> &&promise);
void load_statistics_graph(DialogId dialog_id, const string &token, int64 x, void load_statistics_graph(DialogId dialog_id, string token, int64 x,
Promise<td_api::object_ptr<td_api::StatisticalGraph>> &&promise); Promise<td_api::object_ptr<td_api::StatisticalGraph>> &&promise);
struct CanTransferOwnershipResult { struct CanTransferOwnershipResult {
@ -478,7 +478,7 @@ class ContactsManager final : public Actor {
FileSourceId get_chat_full_file_source_id(ChatId chat_id); FileSourceId get_chat_full_file_source_id(ChatId chat_id);
void reload_chat_full(ChatId chat_id, Promise<Unit> &&promise); void reload_chat_full(ChatId chat_id, Promise<Unit> &&promise);
int32 get_chat_participant_count(ChatId channel_id) const; int32 get_chat_participant_count(ChatId chat_id) const;
bool get_chat_is_active(ChatId chat_id) const; bool get_chat_is_active(ChatId chat_id) const;
ChannelId get_chat_migrated_to_channel_id(ChatId chat_id) const; ChannelId get_chat_migrated_to_channel_id(ChatId chat_id) const;
DialogParticipantStatus get_chat_status(ChatId chat_id) const; DialogParticipantStatus get_chat_status(ChatId chat_id) const;
@ -489,7 +489,7 @@ class ContactsManager final : public Actor {
bool have_min_channel(ChannelId channel_id) const; bool have_min_channel(ChannelId channel_id) const;
bool have_channel_force(ChannelId channel_id); bool have_channel_force(ChannelId channel_id);
bool get_channel(ChannelId channel_id, int left_tries, Promise<Unit> &&promise); bool get_channel(ChannelId channel_id, int left_tries, Promise<Unit> &&promise);
void reload_channel(ChannelId chnanel_id, Promise<Unit> &&promise); void reload_channel(ChannelId channel_id, Promise<Unit> &&promise);
void load_channel_full(ChannelId channel_id, bool force, Promise<Unit> &&promise, const char *source); void load_channel_full(ChannelId channel_id, bool force, Promise<Unit> &&promise, const char *source);
FileSourceId get_channel_full_file_source_id(ChannelId channel_id); FileSourceId get_channel_full_file_source_id(ChannelId channel_id);
void reload_channel_full(ChannelId channel_id, Promise<Unit> &&promise, const char *source); void reload_channel_full(ChannelId channel_id, Promise<Unit> &&promise, const char *source);
@ -583,7 +583,7 @@ class ContactsManager final : public Actor {
static tl_object_ptr<td_api::StatisticalGraph> convert_stats_graph(tl_object_ptr<telegram_api::StatsGraph> obj); static tl_object_ptr<td_api::StatisticalGraph> convert_stats_graph(tl_object_ptr<telegram_api::StatsGraph> obj);
static double get_percentage_value(double new_value, double old_value); static double get_percentage_value(double part, double total);
static tl_object_ptr<td_api::statisticalValue> convert_stats_absolute_value( static tl_object_ptr<td_api::statisticalValue> convert_stats_absolute_value(
const tl_object_ptr<telegram_api::statsAbsValueAndPrev> &obj); const tl_object_ptr<telegram_api::statsAbsValueAndPrev> &obj);
@ -1164,7 +1164,7 @@ class ContactsManager final : public Actor {
static bool is_valid_username(const string &username); static bool is_valid_username(const string &username);
void on_update_user_name(User *u, UserId user_id, string &&first_name, string &&last_name, string &&username); void on_update_user_name(User *u, UserId user_id, string &&first_name, string &&last_name, string &&username);
void on_update_user_phone_number(User *u, UserId user_id, string &&phone_number); static void on_update_user_phone_number(User *u, UserId user_id, string &&phone_number);
void on_update_user_photo(User *u, UserId user_id, tl_object_ptr<telegram_api::UserProfilePhoto> &&photo, void on_update_user_photo(User *u, UserId user_id, tl_object_ptr<telegram_api::UserProfilePhoto> &&photo,
const char *source); const char *source);
void on_update_user_is_contact(User *u, UserId user_id, bool is_contact, bool is_mutual_contact); void on_update_user_is_contact(User *u, UserId user_id, bool is_contact, bool is_mutual_contact);
@ -1173,7 +1173,7 @@ class ContactsManager final : public Actor {
void do_update_user_photo(User *u, UserId user_id, tl_object_ptr<telegram_api::UserProfilePhoto> &&photo, void do_update_user_photo(User *u, UserId user_id, tl_object_ptr<telegram_api::UserProfilePhoto> &&photo,
const char *source); const char *source);
void do_update_user_photo(User *u, UserId user_id, ProfilePhoto new_photo, bool invalidate_photo_cache, void do_update_user_photo(User *u, UserId user_id, ProfilePhoto &&new_photo, bool invalidate_photo_cache,
const char *source); const char *source);
void upload_profile_photo(FileId file_id, bool is_animation, double main_frame_timestamp, Promise<Unit> &&promise, void upload_profile_photo(FileId file_id, bool is_animation, double main_frame_timestamp, Promise<Unit> &&promise,
@ -1184,12 +1184,12 @@ class ContactsManager final : public Actor {
void register_user_photo(User *u, UserId user_id, const Photo &photo); void register_user_photo(User *u, UserId user_id, const Photo &photo);
void on_update_user_full_is_blocked(UserFull *user_full, UserId user_id, bool is_blocked); static void on_update_user_full_is_blocked(UserFull *user_full, UserId user_id, bool is_blocked);
void on_update_user_full_common_chat_count(UserFull *user_full, UserId user_id, int32 common_chat_count); static void on_update_user_full_common_chat_count(UserFull *user_full, UserId user_id, int32 common_chat_count);
void on_update_user_full_commands(UserFull *user_full, UserId user_id, static void on_update_user_full_commands(UserFull *user_full, UserId user_id,
vector<tl_object_ptr<telegram_api::botCommand>> &&bot_commands); vector<tl_object_ptr<telegram_api::botCommand>> &&bot_commands);
void on_update_user_full_need_phone_number_privacy_exception(UserFull *user_full, UserId user_id, void on_update_user_full_need_phone_number_privacy_exception(UserFull *user_full, UserId user_id,
bool need_phone_number_privacy_exception); bool need_phone_number_privacy_exception) const;
void add_profile_photo_to_cache(UserId user_id, Photo &&photo); void add_profile_photo_to_cache(UserId user_id, Photo &&photo);
bool delete_profile_photo_from_cache(UserId user_id, int64 profile_photo_id, bool send_updates); bool delete_profile_photo_from_cache(UserId user_id, int64 profile_photo_id, bool send_updates);
@ -1197,13 +1197,14 @@ class ContactsManager final : public Actor {
void drop_user_full(UserId user_id); void drop_user_full(UserId user_id);
void on_update_chat_status(Chat *c, ChatId chat_id, DialogParticipantStatus status); void on_update_chat_status(Chat *c, ChatId chat_id, DialogParticipantStatus status);
void on_update_chat_default_permissions(Chat *c, ChatId chat_id, RestrictedRights default_permissions, int32 version); static void on_update_chat_default_permissions(Chat *c, ChatId chat_id, RestrictedRights default_permissions,
int32 version);
void on_update_chat_participant_count(Chat *c, ChatId chat_id, int32 participant_count, int32 version, void on_update_chat_participant_count(Chat *c, ChatId chat_id, int32 participant_count, int32 version,
const string &debug_str); const string &debug_str);
void on_update_chat_photo(Chat *c, ChatId chat_id, tl_object_ptr<telegram_api::ChatPhoto> &&chat_photo_ptr); void on_update_chat_photo(Chat *c, ChatId chat_id, tl_object_ptr<telegram_api::ChatPhoto> &&chat_photo_ptr);
void on_update_chat_title(Chat *c, ChatId chat_id, string &&title); static void on_update_chat_title(Chat *c, ChatId chat_id, string &&title);
void on_update_chat_active(Chat *c, ChatId chat_id, bool is_active); static void on_update_chat_active(Chat *c, ChatId chat_id, bool is_active);
void on_update_chat_migrated_to_channel_id(Chat *c, ChatId chat_id, ChannelId migrated_to_channel_id); static void on_update_chat_migrated_to_channel_id(Chat *c, ChatId chat_id, ChannelId migrated_to_channel_id);
void on_update_chat_full_photo(ChatFull *chat_full, ChatId chat_id, Photo photo); void on_update_chat_full_photo(ChatFull *chat_full, ChatId chat_id, Photo photo);
bool on_update_chat_full_participants_short(ChatFull *chat_full, ChatId chat_id, int32 version); bool on_update_chat_full_participants_short(ChatFull *chat_full, ChatId chat_id, int32 version);
@ -1214,10 +1215,11 @@ class ContactsManager final : public Actor {
void on_update_channel_photo(Channel *c, ChannelId channel_id, void on_update_channel_photo(Channel *c, ChannelId channel_id,
tl_object_ptr<telegram_api::ChatPhoto> &&chat_photo_ptr); tl_object_ptr<telegram_api::ChatPhoto> &&chat_photo_ptr);
void on_update_channel_title(Channel *c, ChannelId channel_id, string &&title); static void on_update_channel_title(Channel *c, ChannelId channel_id, string &&title);
void on_update_channel_username(Channel *c, ChannelId channel_id, string &&username); void on_update_channel_username(Channel *c, ChannelId channel_id, string &&username);
void on_update_channel_status(Channel *c, ChannelId channel_id, DialogParticipantStatus &&status); void on_update_channel_status(Channel *c, ChannelId channel_id, DialogParticipantStatus &&status);
void on_update_channel_default_permissions(Channel *c, ChannelId channel_id, RestrictedRights default_permissions); static void on_update_channel_default_permissions(Channel *c, ChannelId channel_id,
RestrictedRights default_permissions);
void on_update_channel_bot_user_ids(ChannelId channel_id, vector<UserId> &&bot_user_ids); void on_update_channel_bot_user_ids(ChannelId channel_id, vector<UserId> &&bot_user_ids);
@ -1229,9 +1231,10 @@ class ContactsManager final : public Actor {
void on_update_channel_full_location(ChannelFull *channel_full, ChannelId channel_id, const DialogLocation &location); void on_update_channel_full_location(ChannelFull *channel_full, ChannelId channel_id, const DialogLocation &location);
void on_update_channel_full_slow_mode_delay(ChannelFull *channel_full, ChannelId channel_id, int32 slow_mode_delay, void on_update_channel_full_slow_mode_delay(ChannelFull *channel_full, ChannelId channel_id, int32 slow_mode_delay,
int32 slow_mode_next_send_date); int32 slow_mode_next_send_date);
void on_update_channel_full_slow_mode_next_send_date(ChannelFull *channel_full, int32 slow_mode_next_send_date); static void on_update_channel_full_slow_mode_next_send_date(ChannelFull *channel_full,
void on_update_channel_full_bot_user_ids(ChannelFull *channel_full, ChannelId channel_id, int32 slow_mode_next_send_date);
vector<UserId> &&bot_user_ids); static void on_update_channel_full_bot_user_ids(ChannelFull *channel_full, ChannelId channel_id,
vector<UserId> &&bot_user_ids);
void on_channel_status_changed(const Channel *c, ChannelId channel_id, const DialogParticipantStatus &old_status, void on_channel_status_changed(const Channel *c, ChannelId channel_id, const DialogParticipantStatus &old_status,
const DialogParticipantStatus &new_status); const DialogParticipantStatus &new_status);
@ -1245,15 +1248,15 @@ class ContactsManager final : public Actor {
void speculative_add_channel_participant_count(ChannelId channel_id, int32 delta_participant_count, bool by_me); void speculative_add_channel_participant_count(ChannelId channel_id, int32 delta_participant_count, bool by_me);
void speculative_add_channel_user(ChannelId channel_id, UserId user_id, DialogParticipantStatus new_status, void speculative_add_channel_user(ChannelId channel_id, UserId user_id, const DialogParticipantStatus &new_status,
DialogParticipantStatus old_status); const DialogParticipantStatus &old_status);
void drop_chat_photos(ChatId chat_id, bool is_empty, bool drop_chat_full_photo, const char *source); void drop_chat_photos(ChatId chat_id, bool is_empty, bool drop_chat_full_photo, const char *source);
void drop_chat_full(ChatId chat_id); void drop_chat_full(ChatId chat_id);
void drop_channel_photos(ChannelId channel_id, bool is_empty, bool drop_channel_full_photo, const char *source); void drop_channel_photos(ChannelId channel_id, bool is_empty, bool drop_channel_full_photo, const char *source);
void do_invalidate_channel_full(ChannelFull *channel_full, bool need_drop_slow_mode_delay); static void do_invalidate_channel_full(ChannelFull *channel_full, bool need_drop_slow_mode_delay);
void update_user_online_member_count(User *u); void update_user_online_member_count(User *u);
void update_chat_online_member_count(const ChatFull *chat_full, ChatId chat_id, bool is_from_server); void update_chat_online_member_count(const ChatFull *chat_full, ChatId chat_id, bool is_from_server);
@ -1333,7 +1336,7 @@ class ContactsManager final : public Actor {
void update_channel_full(ChannelFull *channel_full, ChannelId channel_id, const char *source, void update_channel_full(ChannelFull *channel_full, ChannelId channel_id, const char *source,
bool from_database = false); bool from_database = false);
bool is_chat_full_outdated(const ChatFull *chat_full, const Chat *c, ChatId chat_id); static bool is_chat_full_outdated(const ChatFull *chat_full, const Chat *c, ChatId chat_id);
bool is_user_contact(const User *u, UserId user_id, bool is_mutual) const; bool is_user_contact(const User *u, UserId user_id, bool is_mutual) const;
@ -1362,8 +1365,8 @@ class ContactsManager final : public Actor {
void on_clear_imported_contacts(vector<Contact> &&contacts, vector<size_t> contacts_unique_id, void on_clear_imported_contacts(vector<Contact> &&contacts, vector<size_t> contacts_unique_id,
std::pair<vector<size_t>, vector<Contact>> &&to_add, Promise<Unit> &&promise); std::pair<vector<size_t>, vector<Contact>> &&to_add, Promise<Unit> &&promise);
void send_update_chat_member(DialogId dialog_id, UserId agent_user_id, int32 date, DialogInviteLink invite_link, void send_update_chat_member(DialogId dialog_id, UserId agent_user_id, int32 date,
const DialogParticipant &old_dialog_participant, const DialogInviteLink &invite_link, const DialogParticipant &old_dialog_participant,
const DialogParticipant &new_dialog_participant); const DialogParticipant &new_dialog_participant);
static vector<td_api::object_ptr<td_api::chatNearby>> get_chats_nearby_object( static vector<td_api::object_ptr<td_api::chatNearby>> get_chats_nearby_object(
@ -1397,8 +1400,8 @@ class ContactsManager final : public Actor {
void add_chat_participant(ChatId chat_id, UserId user_id, int32 forward_limit, Promise<Unit> &&promise); void add_chat_participant(ChatId chat_id, UserId user_id, int32 forward_limit, Promise<Unit> &&promise);
void add_channel_participant(ChannelId channel_id, UserId user_id, Promise<Unit> &&promise, void add_channel_participant(ChannelId channel_id, UserId user_id, const DialogParticipantStatus &old_status,
DialogParticipantStatus old_status); Promise<Unit> &&promise);
void add_channel_participants(ChannelId channel_id, const vector<UserId> &user_ids, Promise<Unit> &&promise); void add_channel_participants(ChannelId channel_id, const vector<UserId> &user_ids, Promise<Unit> &&promise);
@ -1467,7 +1470,7 @@ class ContactsManager final : public Actor {
static td_api::object_ptr<td_api::updateSupergroup> get_update_unknown_supergroup_object(ChannelId channel_id); static td_api::object_ptr<td_api::updateSupergroup> get_update_unknown_supergroup_object(ChannelId channel_id);
tl_object_ptr<td_api::supergroup> get_supergroup_object(ChannelId channel_id, const Channel *c) const; static tl_object_ptr<td_api::supergroup> get_supergroup_object(ChannelId channel_id, const Channel *c);
tl_object_ptr<td_api::supergroupFullInfo> get_supergroup_full_info_object(const ChannelFull *channel_full, tl_object_ptr<td_api::supergroupFullInfo> get_supergroup_full_info_object(const ChannelFull *channel_full,
ChannelId channel_id) const; ChannelId channel_id) const;
@ -1520,11 +1523,11 @@ class ContactsManager final : public Actor {
DialogParticipantStatus status, DialogParticipantStatus old_status, DialogParticipantStatus status, DialogParticipantStatus old_status,
Promise<Unit> &&promise); Promise<Unit> &&promise);
void promote_channel_participant(ChannelId channel_id, UserId user_id, DialogParticipantStatus status, void promote_channel_participant(ChannelId channel_id, UserId user_id, const DialogParticipantStatus &status,
DialogParticipantStatus old_status, Promise<Unit> &&promise); const DialogParticipantStatus &old_status, Promise<Unit> &&promise);
void restrict_channel_participant(ChannelId channel_id, DialogId participant_dialog_id, void restrict_channel_participant(ChannelId channel_id, DialogId participant_dialog_id,
DialogParticipantStatus status, DialogParticipantStatus old_status, DialogParticipantStatus &&status, DialogParticipantStatus &&old_status,
Promise<Unit> &&promise); Promise<Unit> &&promise);
void transfer_channel_ownership(ChannelId channel_id, UserId user_id, void transfer_channel_ownership(ChannelId channel_id, UserId user_id,

View File

@ -214,9 +214,9 @@ void CountryInfoManager::do_get_phone_number_info(string phone_number_prefix, st
})); }));
} }
td_api::object_ptr<td_api::phoneNumberInfo> CountryInfoManager::get_phone_number_info_sync(string language_code, td_api::object_ptr<td_api::phoneNumberInfo> CountryInfoManager::get_phone_number_info_sync(const string &language_code,
string phone_number_prefix) { string phone_number_prefix) {
td::remove_if(phone_number_prefix, [](char c) { return c < '0' || c > '9'; }); td::remove_if(phone_number_prefix, [](char c) { return !is_digit(c); });
if (phone_number_prefix.empty()) { if (phone_number_prefix.empty()) {
return td_api::make_object<td_api::phoneNumberInfo>(nullptr, string(), string()); return td_api::make_object<td_api::phoneNumberInfo>(nullptr, string(), string());
} }
@ -401,7 +401,7 @@ void CountryInfoManager::on_get_country_list_impl(const string &language_code,
info.country_code = std::move(c->iso2_); info.country_code = std::move(c->iso2_);
info.default_name = std::move(c->default_name_); info.default_name = std::move(c->default_name_);
info.name = std::move(c->name_); info.name = std::move(c->name_);
info.is_hidden = std::move(c->hidden_); info.is_hidden = c->hidden_;
for (auto &code : c->country_codes_) { for (auto &code : c->country_codes_) {
auto r_calling_code = to_integer_safe<int32>(code->country_code_); auto r_calling_code = to_integer_safe<int32>(code->country_code_);
if (r_calling_code.is_error() || r_calling_code.ok() <= 0) { if (r_calling_code.is_error() || r_calling_code.ok() <= 0) {

View File

@ -34,7 +34,7 @@ class CountryInfoManager final : public Actor {
void get_phone_number_info(string phone_number_prefix, void get_phone_number_info(string phone_number_prefix,
Promise<td_api::object_ptr<td_api::phoneNumberInfo>> &&promise); Promise<td_api::object_ptr<td_api::phoneNumberInfo>> &&promise);
static td_api::object_ptr<td_api::phoneNumberInfo> get_phone_number_info_sync(string language_code, static td_api::object_ptr<td_api::phoneNumberInfo> get_phone_number_info_sync(const string &language_code,
string phone_number_prefix); string phone_number_prefix);
CountryInfoManager(const CountryInfoManager &) = delete; CountryInfoManager(const CountryInfoManager &) = delete;

View File

@ -129,7 +129,7 @@ StringBuilder &operator<<(StringBuilder &string_builder, const DeviceTokenManage
} }
void DeviceTokenManager::register_device(tl_object_ptr<td_api::DeviceToken> device_token_ptr, void DeviceTokenManager::register_device(tl_object_ptr<td_api::DeviceToken> device_token_ptr,
vector<UserId> other_user_ids, const vector<UserId> &other_user_ids,
Promise<td_api::object_ptr<td_api::pushReceiverId>> promise) { Promise<td_api::object_ptr<td_api::pushReceiverId>> promise) {
CHECK(device_token_ptr != nullptr); CHECK(device_token_ptr != nullptr);
TokenType token_type; TokenType token_type;
@ -259,7 +259,7 @@ void DeviceTokenManager::register_device(tl_object_ptr<td_api::DeviceToken> devi
if (encrypt != info.encrypt) { if (encrypt != info.encrypt) {
if (encrypt) { if (encrypt) {
constexpr size_t ENCRYPTION_KEY_LENGTH = 256; constexpr size_t ENCRYPTION_KEY_LENGTH = 256;
constexpr int64 MIN_ENCRYPTION_KEY_ID = static_cast<int64>(10000000000000ll); constexpr auto MIN_ENCRYPTION_KEY_ID = static_cast<int64>(10000000000000ll);
info.encryption_key.resize(ENCRYPTION_KEY_LENGTH); info.encryption_key.resize(ENCRYPTION_KEY_LENGTH);
while (true) { while (true) {
Random::secure_bytes(info.encryption_key); Random::secure_bytes(info.encryption_key);

View File

@ -26,7 +26,7 @@ class DeviceTokenManager final : public NetQueryCallback {
public: public:
explicit DeviceTokenManager(ActorShared<> parent) : parent_(std::move(parent)) { explicit DeviceTokenManager(ActorShared<> parent) : parent_(std::move(parent)) {
} }
void register_device(tl_object_ptr<td_api::DeviceToken> device_token_ptr, vector<UserId> other_user_ids, void register_device(tl_object_ptr<td_api::DeviceToken> device_token_ptr, const vector<UserId> &other_user_ids,
Promise<td_api::object_ptr<td_api::pushReceiverId>> promise); Promise<td_api::object_ptr<td_api::pushReceiverId>> promise);
void reregister_device(); void reregister_device();

View File

@ -27,7 +27,7 @@ int DhCache::is_good_prime(Slice prime_str) const {
if (value == "bad") { if (value == "bad") {
return 0; return 0;
} }
CHECK(value == ""); CHECK(value.empty());
return -1; return -1;
} }

View File

@ -46,7 +46,7 @@ void DialogAction::init(Type type, string emoji) {
} }
} }
void DialogAction::init(Type type, int32 message_id, string emoji, string data) { void DialogAction::init(Type type, int32 message_id, string emoji, const string &data) {
if (ServerMessageId(message_id).is_valid() && is_valid_emoji(emoji) && check_utf8(data)) { if (ServerMessageId(message_id).is_valid() && is_valid_emoji(emoji) && check_utf8(data)) {
type_ = type; type_ = type;
progress_ = message_id; progress_ = message_id;
@ -199,7 +199,7 @@ DialogAction::DialogAction(telegram_api::object_ptr<telegram_api::SendMessageAct
case telegram_api::sendMessageEmojiInteraction::ID: { case telegram_api::sendMessageEmojiInteraction::ID: {
auto emoji_interaction_action = move_tl_object_as<telegram_api::sendMessageEmojiInteraction>(action); auto emoji_interaction_action = move_tl_object_as<telegram_api::sendMessageEmojiInteraction>(action);
init(Type::ClickingAnimatedEmoji, emoji_interaction_action->msg_id_, init(Type::ClickingAnimatedEmoji, emoji_interaction_action->msg_id_,
std::move(emoji_interaction_action->emoticon_), std::move(emoji_interaction_action->interaction_->data_)); std::move(emoji_interaction_action->emoticon_), emoji_interaction_action->interaction_->data_);
break; break;
} }
default: default:

View File

@ -49,7 +49,7 @@ class DialogAction {
void init(Type type, string emoji); void init(Type type, string emoji);
void init(Type type, int32 message_id, string emoji, string data); void init(Type type, int32 message_id, string emoji, const string &data);
static bool is_valid_emoji(string &emoji); static bool is_valid_emoji(string &emoji);

View File

@ -458,7 +458,7 @@ DialogParticipantStatus get_dialog_participant_status(const tl_object_ptr<td_api
} }
DialogParticipantStatus get_dialog_participant_status(bool can_be_edited, DialogParticipantStatus get_dialog_participant_status(bool can_be_edited,
const tl_object_ptr<telegram_api::chatAdminRights> &admin_rights, tl_object_ptr<telegram_api::chatAdminRights> &&admin_rights,
string rank) { string rank) {
bool can_change_info = (admin_rights->flags_ & telegram_api::chatAdminRights::CHANGE_INFO_MASK) != 0; bool can_change_info = (admin_rights->flags_ & telegram_api::chatAdminRights::CHANGE_INFO_MASK) != 0;
bool can_post_messages = (admin_rights->flags_ & telegram_api::chatAdminRights::POST_MESSAGES_MASK) != 0; bool can_post_messages = (admin_rights->flags_ & telegram_api::chatAdminRights::POST_MESSAGES_MASK) != 0;
@ -480,8 +480,8 @@ DialogParticipantStatus get_dialog_participant_status(bool can_be_edited,
can_pin_messages, can_promote_members, can_manage_calls); can_pin_messages, can_promote_members, can_manage_calls);
} }
DialogParticipantStatus get_dialog_participant_status( DialogParticipantStatus get_dialog_participant_status(bool is_member,
bool is_member, const tl_object_ptr<telegram_api::chatBannedRights> &banned_rights) { tl_object_ptr<telegram_api::chatBannedRights> &&banned_rights) {
bool can_view_messages = (banned_rights->flags_ & telegram_api::chatBannedRights::VIEW_MESSAGES_MASK) == 0; bool can_view_messages = (banned_rights->flags_ & telegram_api::chatBannedRights::VIEW_MESSAGES_MASK) == 0;
if (!can_view_messages) { if (!can_view_messages) {
return DialogParticipantStatus::Banned(banned_rights->until_date_); return DialogParticipantStatus::Banned(banned_rights->until_date_);
@ -616,7 +616,7 @@ StringBuilder &operator<<(StringBuilder &string_builder, const RestrictedRights
return string_builder; return string_builder;
} }
RestrictedRights get_restricted_rights(const tl_object_ptr<telegram_api::chatBannedRights> &banned_rights) { RestrictedRights get_restricted_rights(tl_object_ptr<telegram_api::chatBannedRights> &&banned_rights) {
if (banned_rights == nullptr) { if (banned_rights == nullptr) {
return RestrictedRights(false, false, false, false, false, false, false, false, false, false, false); return RestrictedRights(false, false, false, false, false, false, false, false, false, false, false);
} }
@ -657,14 +657,14 @@ RestrictedRights get_restricted_rights(const td_api::object_ptr<td_api::chatPerm
DialogParticipant::DialogParticipant(DialogId dialog_id, UserId inviter_user_id, int32 joined_date, DialogParticipant::DialogParticipant(DialogId dialog_id, UserId inviter_user_id, int32 joined_date,
DialogParticipantStatus status) DialogParticipantStatus status)
: dialog_id(dialog_id), inviter_user_id(inviter_user_id), joined_date(joined_date), status(status) { : dialog_id(dialog_id), inviter_user_id(inviter_user_id), joined_date(joined_date), status(std::move(status)) {
if (!inviter_user_id.is_valid() && inviter_user_id != UserId()) { if (!inviter_user_id.is_valid() && inviter_user_id != UserId()) {
LOG(ERROR) << "Receive inviter " << inviter_user_id; LOG(ERROR) << "Receive inviter " << inviter_user_id;
inviter_user_id = UserId(); this->inviter_user_id = UserId();
} }
if (joined_date < 0) { if (joined_date < 0) {
LOG(ERROR) << "Receive date " << joined_date; LOG(ERROR) << "Receive date " << joined_date;
joined_date = 0; this->joined_date = 0;
} }
} }

View File

@ -397,7 +397,7 @@ struct DialogParticipant {
DialogParticipant() = default; DialogParticipant() = default;
DialogParticipant(DialogId user_id, UserId inviter_user_id, int32 joined_date, DialogParticipantStatus status); DialogParticipant(DialogId dialog_id, UserId inviter_user_id, int32 joined_date, DialogParticipantStatus status);
DialogParticipant(tl_object_ptr<telegram_api::ChatParticipant> &&participant_ptr, int32 chat_creation_date, DialogParticipant(tl_object_ptr<telegram_api::ChatParticipant> &&participant_ptr, int32 chat_creation_date,
bool is_creator); bool is_creator);
@ -508,13 +508,13 @@ DialogParticipantsFilter get_dialog_participants_filter(const tl_object_ptr<td_a
DialogParticipantStatus get_dialog_participant_status(const tl_object_ptr<td_api::ChatMemberStatus> &status); DialogParticipantStatus get_dialog_participant_status(const tl_object_ptr<td_api::ChatMemberStatus> &status);
DialogParticipantStatus get_dialog_participant_status(bool can_be_edited, DialogParticipantStatus get_dialog_participant_status(bool can_be_edited,
const tl_object_ptr<telegram_api::chatAdminRights> &admin_rights, tl_object_ptr<telegram_api::chatAdminRights> &&admin_rights,
string rank); string rank);
DialogParticipantStatus get_dialog_participant_status( DialogParticipantStatus get_dialog_participant_status(bool is_member,
bool is_member, const tl_object_ptr<telegram_api::chatBannedRights> &banned_rights); tl_object_ptr<telegram_api::chatBannedRights> &&banned_rights);
RestrictedRights get_restricted_rights(const tl_object_ptr<telegram_api::chatBannedRights> &banned_rights); RestrictedRights get_restricted_rights(tl_object_ptr<telegram_api::chatBannedRights> &&banned_rights);
RestrictedRights get_restricted_rights(const td_api::object_ptr<td_api::chatPermissions> &permissions); RestrictedRights get_restricted_rights(const td_api::object_ptr<td_api::chatPermissions> &permissions);

View File

@ -573,7 +573,7 @@ SecretInputMedia DocumentsManager::get_secret_input_media(FileId document_file_i
return SecretInputMedia{}; return SecretInputMedia{};
} }
vector<tl_object_ptr<secret_api::DocumentAttribute>> attributes; vector<tl_object_ptr<secret_api::DocumentAttribute>> attributes;
if (document->file_name.size()) { if (!document->file_name.empty()) {
attributes.push_back(make_tl_object<secret_api::documentAttributeFilename>(document->file_name)); attributes.push_back(make_tl_object<secret_api::documentAttributeFilename>(document->file_name));
} }
return SecretInputMedia{ return SecretInputMedia{
@ -604,7 +604,7 @@ tl_object_ptr<telegram_api::InputMedia> DocumentsManager::get_input_media(
CHECK(document != nullptr); CHECK(document != nullptr);
vector<tl_object_ptr<telegram_api::DocumentAttribute>> attributes; vector<tl_object_ptr<telegram_api::DocumentAttribute>> attributes;
if (document->file_name.size()) { if (!document->file_name.empty()) {
attributes.push_back(make_tl_object<telegram_api::documentAttributeFilename>(document->file_name)); attributes.push_back(make_tl_object<telegram_api::documentAttributeFilename>(document->file_name));
} }
int32 flags = 0; int32 flags = 0;

View File

@ -54,7 +54,8 @@ class FileReferenceManager final : public Actor {
using NodeId = FileId; using NodeId = FileId;
void repair_file_reference(NodeId node_id, Promise<> promise); void repair_file_reference(NodeId node_id, Promise<> promise);
void reload_photo(PhotoSizeSource source, Promise<Unit> promise);
static void reload_photo(PhotoSizeSource source, Promise<Unit> promise);
bool add_file_source(NodeId node_id, FileSourceId file_source_id); bool add_file_source(NodeId node_id, FileSourceId file_source_id);

View File

@ -377,7 +377,7 @@ class Global final : public ActorContext {
void set_dh_config(std::shared_ptr<DhConfig> new_dh_config) { void set_dh_config(std::shared_ptr<DhConfig> new_dh_config) {
#if !TD_HAVE_ATOMIC_SHARED_PTR #if !TD_HAVE_ATOMIC_SHARED_PTR
std::lock_guard<std::mutex> guard(dh_config_mutex_); std::lock_guard<std::mutex> guard(dh_config_mutex_);
dh_config_ = new_dh_config; dh_config_ = std::move(new_dh_config);
#else #else
atomic_store(&dh_config_, std::move(new_dh_config)); atomic_store(&dh_config_, std::move(new_dh_config));
#endif #endif

View File

@ -1764,6 +1764,7 @@ void GroupCallManager::on_update_group_call_participants(
}); });
td_->create_handler<GetGroupCallParticipantQuery>(std::move(query_promise)) td_->create_handler<GetGroupCallParticipantQuery>(std::move(query_promise))
->send(input_group_call_id, std::move(input_peers), {}); ->send(input_group_call_id, std::move(input_peers), {});
return;
} }
} }
@ -1976,8 +1977,9 @@ void GroupCallManager::on_sync_group_call_participants(InputGroupCallId input_gr
} }
} }
GroupCallParticipantOrder GroupCallManager::get_real_participant_order( GroupCallParticipantOrder GroupCallManager::get_real_participant_order(bool can_self_unmute,
bool can_self_unmute, const GroupCallParticipant &participant, const GroupCallParticipants *participants) const { const GroupCallParticipant &participant,
const GroupCallParticipants *participants) {
auto real_order = participant.get_real_order(can_self_unmute, participants->joined_date_asc, false); auto real_order = participant.get_real_order(can_self_unmute, participants->joined_date_asc, false);
if (real_order >= participants->min_order) { if (real_order >= participants->min_order) {
return real_order; return real_order;
@ -2273,7 +2275,7 @@ std::pair<int32, int32> GroupCallManager::process_group_call_participant(InputGr
} }
on_add_group_call_participant(input_group_call_id, participants->participants.back().dialog_id); on_add_group_call_participant(input_group_call_id, participants->participants.back().dialog_id);
on_participant_speaking_in_group_call(input_group_call_id, participants->participants.back()); on_participant_speaking_in_group_call(input_group_call_id, participants->participants.back());
return {diff, participant.video_diff}; return {diff, participants->participants.back().video_diff};
} }
void GroupCallManager::on_add_group_call_participant(InputGroupCallId input_group_call_id, void GroupCallManager::on_add_group_call_participant(InputGroupCallId input_group_call_id,
@ -4106,7 +4108,7 @@ InputGroupCallId GroupCallManager::update_group_call(const tl_object_ptr<telegra
auto group_call = static_cast<const telegram_api::groupCall *>(group_call_ptr.get()); auto group_call = static_cast<const telegram_api::groupCall *>(group_call_ptr.get());
input_group_call_id = InputGroupCallId(group_call->id_, group_call->access_hash_); input_group_call_id = InputGroupCallId(group_call->id_, group_call->access_hash_);
call.is_active = true; call.is_active = true;
call.title = std::move(group_call->title_); call.title = group_call->title_;
call.start_subscribed = group_call->schedule_start_subscribed_; call.start_subscribed = group_call->schedule_start_subscribed_;
call.mute_new_participants = group_call->join_muted_; call.mute_new_participants = group_call->join_muted_;
call.joined_date_asc = group_call->join_date_asc_; call.joined_date_asc = group_call->join_date_asc_;
@ -4480,8 +4482,10 @@ void GroupCallManager::remove_recent_group_call_speaker(InputGroupCallId input_g
void GroupCallManager::on_group_call_recent_speakers_updated(const GroupCall *group_call, void GroupCallManager::on_group_call_recent_speakers_updated(const GroupCall *group_call,
GroupCallRecentSpeakers *recent_speakers) { GroupCallRecentSpeakers *recent_speakers) {
if (group_call == nullptr || !group_call->is_inited || recent_speakers->is_changed) { if (group_call == nullptr || !group_call->is_inited || recent_speakers->is_changed) {
LOG(INFO) << "Don't need to send update of recent speakers in " << group_call->group_call_id << " from " if (group_call != nullptr) {
<< group_call->dialog_id; LOG(INFO) << "Don't need to send update of recent speakers in " << group_call->group_call_id << " from "
<< group_call->dialog_id;
}
return; return;
} }
@ -4677,12 +4681,12 @@ vector<td_api::object_ptr<td_api::groupCallRecentSpeaker>> GroupCallManager::get
} }
tl_object_ptr<td_api::groupCall> GroupCallManager::get_group_call_object( tl_object_ptr<td_api::groupCall> GroupCallManager::get_group_call_object(
const GroupCall *group_call, vector<td_api::object_ptr<td_api::groupCallRecentSpeaker>> recent_speakers) const { const GroupCall *group_call, vector<td_api::object_ptr<td_api::groupCallRecentSpeaker>> recent_speakers) {
CHECK(group_call != nullptr); CHECK(group_call != nullptr);
CHECK(group_call->is_inited); CHECK(group_call->is_inited);
int32 scheduled_start_date = group_call->scheduled_start_date; int32 scheduled_start_date = group_call->scheduled_start_date;
bool is_active = scheduled_start_date == 0 ? group_call->is_active : 0; bool is_active = scheduled_start_date == 0 ? group_call->is_active : false;
bool is_joined = group_call->is_joined && !group_call->is_being_left; bool is_joined = group_call->is_joined && !group_call->is_being_left;
bool start_subscribed = get_group_call_start_subscribed(group_call); bool start_subscribed = get_group_call_start_subscribed(group_call);
bool is_my_video_enabled = get_group_call_is_my_video_enabled(group_call); bool is_my_video_enabled = get_group_call_is_my_video_enabled(group_call);
@ -4703,7 +4707,7 @@ tl_object_ptr<td_api::groupCall> GroupCallManager::get_group_call_object(
} }
tl_object_ptr<td_api::updateGroupCall> GroupCallManager::get_update_group_call_object( tl_object_ptr<td_api::updateGroupCall> GroupCallManager::get_update_group_call_object(
const GroupCall *group_call, vector<td_api::object_ptr<td_api::groupCallRecentSpeaker>> recent_speakers) const { const GroupCall *group_call, vector<td_api::object_ptr<td_api::groupCallRecentSpeaker>> recent_speakers) {
return td_api::make_object<td_api::updateGroupCall>(get_group_call_object(group_call, std::move(recent_speakers))); return td_api::make_object<td_api::updateGroupCall>(get_group_call_object(group_call, std::move(recent_speakers)));
} }

View File

@ -235,8 +235,9 @@ class GroupCallManager final : public Actor {
void on_sync_group_call_participants(InputGroupCallId input_group_call_id, void on_sync_group_call_participants(InputGroupCallId input_group_call_id,
Result<tl_object_ptr<telegram_api::phone_groupCall>> &&result); Result<tl_object_ptr<telegram_api::phone_groupCall>> &&result);
GroupCallParticipantOrder get_real_participant_order(bool can_self_unmute, const GroupCallParticipant &participant, static GroupCallParticipantOrder get_real_participant_order(bool can_self_unmute,
const GroupCallParticipants *participants) const; const GroupCallParticipant &participant,
const GroupCallParticipants *participants);
void process_my_group_call_participant(InputGroupCallId input_group_call_id, GroupCallParticipant &&participant); void process_my_group_call_participant(InputGroupCallId input_group_call_id, GroupCallParticipant &&participant);
@ -244,8 +245,8 @@ class GroupCallManager final : public Actor {
vector<tl_object_ptr<telegram_api::groupCallParticipant>> &&participants, vector<tl_object_ptr<telegram_api::groupCallParticipant>> &&participants,
int32 version, const string &offset, bool is_load, bool is_sync); int32 version, const string &offset, bool is_load, bool is_sync);
bool update_group_call_participant_can_be_muted(bool can_manage, const GroupCallParticipants *participants, static bool update_group_call_participant_can_be_muted(bool can_manage, const GroupCallParticipants *participants,
GroupCallParticipant &participant); GroupCallParticipant &participant);
void update_group_call_participants_can_be_muted(InputGroupCallId input_group_call_id, bool can_manage, void update_group_call_participants_can_be_muted(InputGroupCallId input_group_call_id, bool can_manage,
GroupCallParticipants *participants); GroupCallParticipants *participants);
@ -360,11 +361,11 @@ class GroupCallManager final : public Actor {
vector<td_api::object_ptr<td_api::groupCallRecentSpeaker>> get_recent_speakers(const GroupCall *group_call, vector<td_api::object_ptr<td_api::groupCallRecentSpeaker>> get_recent_speakers(const GroupCall *group_call,
bool for_update); bool for_update);
tl_object_ptr<td_api::updateGroupCall> get_update_group_call_object( static tl_object_ptr<td_api::updateGroupCall> get_update_group_call_object(
const GroupCall *group_call, vector<td_api::object_ptr<td_api::groupCallRecentSpeaker>> recent_speakers) const; const GroupCall *group_call, vector<td_api::object_ptr<td_api::groupCallRecentSpeaker>> recent_speakers);
tl_object_ptr<td_api::groupCall> get_group_call_object( static tl_object_ptr<td_api::groupCall> get_group_call_object(
const GroupCall *group_call, vector<td_api::object_ptr<td_api::groupCallRecentSpeaker>> recent_speakers) const; const GroupCall *group_call, vector<td_api::object_ptr<td_api::groupCallRecentSpeaker>> recent_speakers);
tl_object_ptr<td_api::updateGroupCallParticipant> get_update_group_call_participant_object( tl_object_ptr<td_api::updateGroupCallParticipant> get_update_group_call_participant_object(
GroupCallId group_call_id, const GroupCallParticipant &participant); GroupCallId group_call_id, const GroupCallParticipant &participant);

View File

@ -20,7 +20,7 @@ GroupCallParticipant::GroupCallParticipant(const tl_object_ptr<telegram_api::gro
int32 call_version) { int32 call_version) {
CHECK(participant != nullptr); CHECK(participant != nullptr);
dialog_id = DialogId(participant->peer_); dialog_id = DialogId(participant->peer_);
about = std::move(participant->about_); about = participant->about_;
audio_source = participant->source_; audio_source = participant->source_;
server_is_muted_by_themselves = participant->can_self_unmute_; server_is_muted_by_themselves = participant->can_self_unmute_;
server_is_muted_by_admin = participant->muted_ && !participant->can_self_unmute_; server_is_muted_by_admin = participant->muted_ && !participant->can_self_unmute_;

View File

@ -488,7 +488,11 @@ void InlineQueriesManager::answer_inline_query(int64 inline_query_id, bool is_pe
if (first_name.empty()) { if (first_name.empty()) {
return promise.set_error(Status::Error(400, "Field \"first_name\" must be non-empty")); return promise.set_error(Status::Error(400, "Field \"first_name\" must be non-empty"));
} }
title = last_name.empty() ? first_name : first_name + " " + last_name; if (last_name.empty()) {
title = std::move(first_name);
} else {
title = PSTRING() << first_name << ' ' << last_name;
}
description = std::move(phone_number); description = std::move(phone_number);
thumbnail_url = std::move(contact->thumbnail_url_); thumbnail_url = std::move(contact->thumbnail_url_);
if (!thumbnail_url.empty()) { if (!thumbnail_url.empty()) {
@ -1460,7 +1464,7 @@ void InlineQueriesManager::on_get_inline_query_results(DialogId dialog_id, UserI
if (result->type_ == "article") { if (result->type_ == "article") {
auto article = make_tl_object<td_api::inlineQueryResultArticle>(); auto article = make_tl_object<td_api::inlineQueryResultArticle>();
article->id_ = std::move(result->id_); article->id_ = std::move(result->id_);
article->url_ = get_web_document_url(std::move(result->content_)); article->url_ = get_web_document_url(result->content_);
if (result->url_.empty()) { if (result->url_.empty()) {
article->hide_url_ = true; article->hide_url_ = true;
} else { } else {

View File

@ -220,7 +220,7 @@ int32 get_json_value_int(telegram_api::object_ptr<telegram_api::JSONValue> &&jso
string get_json_value_string(telegram_api::object_ptr<telegram_api::JSONValue> &&json_value, Slice name) { string get_json_value_string(telegram_api::object_ptr<telegram_api::JSONValue> &&json_value, Slice name) {
CHECK(json_value != nullptr); CHECK(json_value != nullptr);
if (json_value->get_id() == telegram_api::jsonString::ID) { if (json_value->get_id() == telegram_api::jsonString::ID) {
return std::move(static_cast<const telegram_api::jsonString *>(json_value.get())->value_); return std::move(static_cast<telegram_api::jsonString *>(json_value.get())->value_);
} }
LOG(ERROR) << "Expected String as " << name << ", but found " << to_string(json_value); LOG(ERROR) << "Expected String as " << name << ", but found " << to_string(json_value);
return string(); return string();

View File

@ -170,7 +170,7 @@ static string load_database_language_base_language_code(SqliteKeyValue *kv) {
return kv->get("!base_language_code"); return kv->get("!base_language_code");
} }
LanguagePackManager::LanguageDatabase *LanguagePackManager::add_language_database(const string &path) { LanguagePackManager::LanguageDatabase *LanguagePackManager::add_language_database(string path) {
auto it = language_databases_.find(path); auto it = language_databases_.find(path);
if (it != language_databases_.end()) { if (it != language_databases_.end()) {
return it->second.get(); return it->second.get();
@ -395,11 +395,11 @@ void LanguagePackManager::on_language_pack_version_changed(bool is_base, int32 n
LOG(INFO) << (is_base ? "Base" : "Main") << " language pack " << language_code << " vesrion has changed to " LOG(INFO) << (is_base ? "Base" : "Main") << " language pack " << language_code << " vesrion has changed to "
<< new_version; << new_version;
send_language_get_difference_query(language, language_code, version, Auto()); send_language_get_difference_query(language, std::move(language_code), version, Auto());
} }
void LanguagePackManager::send_language_get_difference_query(Language *language, const string &language_code, void LanguagePackManager::send_language_get_difference_query(Language *language, string language_code, int32 version,
int32 version, Promise<Unit> &&promise) { Promise<Unit> &&promise) {
std::lock_guard<std::mutex> lock(language->mutex_); std::lock_guard<std::mutex> lock(language->mutex_);
language->get_difference_queries_.push_back(std::move(promise)); language->get_difference_queries_.push_back(std::move(promise));
if (language->has_get_difference_query_) { if (language->has_get_difference_query_) {
@ -1179,7 +1179,7 @@ void LanguagePackManager::synchronize_language_pack(string language_code, Promis
if (version == -1) { if (version == -1) {
version = 0; version = 0;
} }
send_language_get_difference_query(language, language_code, version, std::move(promise)); send_language_get_difference_query(language, std::move(language_code), version, std::move(promise));
} }
static td_api::object_ptr<td_api::LanguagePackStringValue> copy_language_pack_string_value( static td_api::object_ptr<td_api::LanguagePackStringValue> copy_language_pack_string_value(
@ -1294,7 +1294,7 @@ bool LanguagePackManager::is_valid_key(Slice key) {
} }
void LanguagePackManager::save_strings_to_database(SqliteKeyValue *kv, int32 new_version, bool new_is_full, void LanguagePackManager::save_strings_to_database(SqliteKeyValue *kv, int32 new_version, bool new_is_full,
int32 new_key_count, vector<std::pair<string, string>> strings) { int32 new_key_count, vector<std::pair<string, string>> &&strings) {
LOG(DEBUG) << "Save to database a language pack with new version " << new_version << " and " << strings.size() LOG(DEBUG) << "Save to database a language pack with new version " << new_version << " and " << strings.size()
<< " new strings"; << " new strings";
if (new_version == -1 && strings.empty()) { if (new_version == -1 && strings.empty()) {
@ -1314,7 +1314,7 @@ void LanguagePackManager::save_strings_to_database(SqliteKeyValue *kv, int32 new
} }
kv->begin_write_transaction().ensure(); kv->begin_write_transaction().ensure();
for (auto str : strings) { for (const auto &str : strings) {
if (!is_valid_key(str.first)) { if (!is_valid_key(str.first)) {
LOG(ERROR) << "Have invalid key \"" << str.first << '"'; LOG(ERROR) << "Have invalid key \"" << str.first << '"';
continue; continue;
@ -1339,7 +1339,7 @@ void LanguagePackManager::save_strings_to_database(SqliteKeyValue *kv, int32 new
} }
void LanguagePackManager::on_get_language_pack_strings( void LanguagePackManager::on_get_language_pack_strings(
string language_pack, string language_code, int32 version, bool is_diff, vector<string> keys, string language_pack, string language_code, int32 version, bool is_diff, vector<string> &&keys,
vector<tl_object_ptr<telegram_api::LangPackString>> results, vector<tl_object_ptr<telegram_api::LangPackString>> results,
Promise<td_api::object_ptr<td_api::languagePackStrings>> promise) { Promise<td_api::object_ptr<td_api::languagePackStrings>> promise) {
Language *language = get_language(database_, language_pack, language_code); Language *language = get_language(database_, language_pack, language_code);
@ -1370,7 +1370,7 @@ void LanguagePackManager::on_get_language_pack_strings(
CHECK(result != nullptr); CHECK(result != nullptr);
switch (result->get_id()) { switch (result->get_id()) {
case telegram_api::langPackString::ID: { case telegram_api::langPackString::ID: {
auto str = static_cast<telegram_api::langPackString *>(result.get()); auto str = telegram_api::move_object_as<telegram_api::langPackString>(result);
auto it = language->ordinary_strings_.find(str->key_); auto it = language->ordinary_strings_.find(str->key_);
if (it == language->ordinary_strings_.end()) { if (it == language->ordinary_strings_.end()) {
key_count_delta++; key_count_delta++;
@ -1383,11 +1383,11 @@ void LanguagePackManager::on_get_language_pack_strings(
if (is_diff) { if (is_diff) {
strings.push_back(get_language_pack_string_object(*it)); strings.push_back(get_language_pack_string_object(*it));
} }
database_strings.emplace_back(str->key_, PSTRING() << '1' << it->second); database_strings.emplace_back(std::move(str->key_), PSTRING() << '1' << it->second);
break; break;
} }
case telegram_api::langPackStringPluralized::ID: { case telegram_api::langPackStringPluralized::ID: {
auto str = static_cast<const telegram_api::langPackStringPluralized *>(result.get()); auto str = telegram_api::move_object_as<telegram_api::langPackStringPluralized>(result);
PluralizedString value{std::move(str->zero_value_), std::move(str->one_value_), PluralizedString value{std::move(str->zero_value_), std::move(str->one_value_),
std::move(str->two_value_), std::move(str->few_value_), std::move(str->two_value_), std::move(str->few_value_),
std::move(str->many_value_), std::move(str->other_value_)}; std::move(str->many_value_), std::move(str->other_value_)};
@ -1404,20 +1404,21 @@ void LanguagePackManager::on_get_language_pack_strings(
strings.push_back(get_language_pack_string_object(*it)); strings.push_back(get_language_pack_string_object(*it));
} }
database_strings.emplace_back( database_strings.emplace_back(
str->key_, PSTRING() << '2' << it->second.zero_value_ << '\x00' << it->second.one_value_ << '\x00' std::move(str->key_), PSTRING()
<< it->second.two_value_ << '\x00' << it->second.few_value_ << '\x00' << '2' << it->second.zero_value_ << '\x00' << it->second.one_value_ << '\x00'
<< it->second.many_value_ << '\x00' << it->second.other_value_); << it->second.two_value_ << '\x00' << it->second.few_value_ << '\x00'
<< it->second.many_value_ << '\x00' << it->second.other_value_);
break; break;
} }
case telegram_api::langPackStringDeleted::ID: { case telegram_api::langPackStringDeleted::ID: {
auto str = static_cast<const telegram_api::langPackStringDeleted *>(result.get()); auto str = telegram_api::move_object_as<telegram_api::langPackStringDeleted>(result);
key_count_delta -= static_cast<int32>(language->ordinary_strings_.erase(str->key_)); key_count_delta -= static_cast<int32>(language->ordinary_strings_.erase(str->key_));
key_count_delta -= static_cast<int32>(language->pluralized_strings_.erase(str->key_)); key_count_delta -= static_cast<int32>(language->pluralized_strings_.erase(str->key_));
language->deleted_strings_.insert(std::move(str->key_)); language->deleted_strings_.insert(str->key_);
if (is_diff) { if (is_diff) {
strings.push_back(get_language_pack_string_object(str->key_)); strings.push_back(get_language_pack_string_object(str->key_));
} }
database_strings.emplace_back(str->key_, "3"); database_strings.emplace_back(std::move(str->key_), "3");
break; break;
} }
default: default:
@ -1426,7 +1427,7 @@ void LanguagePackManager::on_get_language_pack_strings(
} }
} }
if (!language->is_full_) { if (!language->is_full_) {
for (auto &key : keys) { for (const auto &key : keys) {
if (!language_has_string_unsafe(language, key)) { if (!language_has_string_unsafe(language, key)) {
LOG(ERROR) << "Doesn't receive key " << key << " from server"; LOG(ERROR) << "Doesn't receive key " << key << " from server";
language->deleted_strings_.insert(key); language->deleted_strings_.insert(key);
@ -1822,7 +1823,7 @@ void LanguagePackManager::delete_language(string language_code, Promise<Unit> &&
} }
} }
Status LanguagePackManager::do_delete_language(string language_code) { Status LanguagePackManager::do_delete_language(const string &language_code) {
add_language(database_, language_pack_, language_code); add_language(database_, language_pack_, language_code);
std::lock_guard<std::mutex> packs_lock(database_->mutex_); std::lock_guard<std::mutex> packs_lock(database_->mutex_);

View File

@ -108,7 +108,7 @@ class LanguagePackManager final : public NetQueryCallback {
static std::mutex language_database_mutex_; static std::mutex language_database_mutex_;
static std::unordered_map<string, unique_ptr<LanguageDatabase>> language_databases_; static std::unordered_map<string, unique_ptr<LanguageDatabase>> language_databases_;
static LanguageDatabase *add_language_database(const string &path); static LanguageDatabase *add_language_database(string path);
static Language *get_language(LanguageDatabase *database, const string &language_pack, const string &language_code); static Language *get_language(LanguageDatabase *database, const string &language_pack, const string &language_code);
static Language *get_language(LanguagePack *language_pack, const string &language_code); static Language *get_language(LanguagePack *language_pack, const string &language_code);
@ -160,25 +160,25 @@ class LanguagePackManager final : public NetQueryCallback {
static bool is_valid_key(Slice key); static bool is_valid_key(Slice key);
void save_strings_to_database(SqliteKeyValue *kv, int32 new_version, bool new_is_full, int32 new_key_count, void save_strings_to_database(SqliteKeyValue *kv, int32 new_version, bool new_is_full, int32 new_key_count,
vector<std::pair<string, string>> strings); vector<std::pair<string, string>> &&strings);
void load_empty_language_pack(const string &language_code); void load_empty_language_pack(const string &language_code);
void on_get_language_pack_strings(string language_pack, string language_code, int32 version, bool is_diff, void on_get_language_pack_strings(string language_pack, string language_code, int32 version, bool is_diff,
vector<string> keys, vector<tl_object_ptr<telegram_api::LangPackString>> results, vector<string> &&keys, vector<tl_object_ptr<telegram_api::LangPackString>> results,
Promise<td_api::object_ptr<td_api::languagePackStrings>> promise); Promise<td_api::object_ptr<td_api::languagePackStrings>> promise);
void on_get_all_language_pack_strings(string language_pack, string language_code, void on_get_all_language_pack_strings(string language_pack, string language_code,
Result<td_api::object_ptr<td_api::languagePackStrings>> r_strings); Result<td_api::object_ptr<td_api::languagePackStrings>> r_strings);
void send_language_get_difference_query(Language *language, const string &language_code, int32 version, void send_language_get_difference_query(Language *language, string language_code, int32 version,
Promise<Unit> &&promise); Promise<Unit> &&promise);
void on_failed_get_difference(string language_pack, string language_code, Status error); void on_failed_get_difference(string language_pack, string language_code, Status error);
void on_get_language_info(const string &language_pack, td_api::languagePackInfo *language_pack_info); void on_get_language_info(const string &language_pack, td_api::languagePackInfo *language_pack_info);
void save_server_language_pack_infos(LanguagePack *pack); static void save_server_language_pack_infos(LanguagePack *pack);
void on_get_languages(vector<tl_object_ptr<telegram_api::langPackLanguage>> languages, string language_pack, void on_get_languages(vector<tl_object_ptr<telegram_api::langPackLanguage>> languages, string language_pack,
bool only_local, Promise<td_api::object_ptr<td_api::localizationTargetInfo>> promise); bool only_local, Promise<td_api::object_ptr<td_api::localizationTargetInfo>> promise);
@ -186,7 +186,7 @@ class LanguagePackManager final : public NetQueryCallback {
void on_get_language(tl_object_ptr<telegram_api::langPackLanguage> lang_pack_language, string language_pack, void on_get_language(tl_object_ptr<telegram_api::langPackLanguage> lang_pack_language, string language_pack,
string language_code, Promise<td_api::object_ptr<td_api::languagePackInfo>> promise); string language_code, Promise<td_api::object_ptr<td_api::languagePackInfo>> promise);
Status do_delete_language(string language_code); Status do_delete_language(const string &language_code);
void on_result(NetQueryPtr query) final; void on_result(NetQueryPtr query) final;

View File

@ -77,7 +77,7 @@ static string get_url_query_hash(bool is_tg, const HttpUrlQuery &url_query) {
// /joinchat/<link> // /joinchat/<link>
return path[1]; return path[1];
} }
if (path.size() >= 1 && path[0].size() >= 2 && (path[0][0] == ' ' || path[0][0] == '+')) { if (!path.empty() && path[0].size() >= 2 && (path[0][0] == ' ' || path[0][0] == '+')) {
// /+<link> // /+<link>
return path[0].substr(1); return path[0].substr(1);
} }
@ -811,7 +811,7 @@ unique_ptr<LinkManager::InternalLink> LinkManager::parse_tg_link_query(Slice que
} else if (path.size() == 1 && path[0] == "passport") { } else if (path.size() == 1 && path[0] == "passport") {
// passport?bot_id=<bot_user_id>&scope=<scope>&public_key=<public_key>&nonce=<nonce> // passport?bot_id=<bot_user_id>&scope=<scope>&public_key=<public_key>&nonce=<nonce>
return get_internal_link_passport(query, url_query.args_); return get_internal_link_passport(query, url_query.args_);
} else if (path.size() >= 1 && path[0] == "settings") { } else if (!path.empty() && path[0] == "settings") {
if (path.size() == 2 && path[1] == "change_number") { if (path.size() == 2 && path[1] == "change_number") {
// settings/change_number // settings/change_number
return td::make_unique<InternalLinkChangePhoneNumber>(); return td::make_unique<InternalLinkChangePhoneNumber>();

View File

@ -34,7 +34,7 @@ class Location {
void init(double latitude, double longitude, double horizontal_accuracy, int64 access_hash); void init(double latitude, double longitude, double horizontal_accuracy, int64 access_hash);
double fix_accuracy(double accuracy); static double fix_accuracy(double accuracy);
public: public:
Location() = default; Location() = default;

File diff suppressed because it is too large Load Diff

View File

@ -1595,7 +1595,7 @@ static void fix_entity_offsets(Slice text, vector<MessageEntity> &entities) {
auto entity_begin = entity.offset; auto entity_begin = entity.offset;
auto entity_end = entity.offset + entity.length; auto entity_end = entity.offset + entity.length;
int32 pos = static_cast<int32>(ptr - begin); auto pos = static_cast<int32>(ptr - begin);
if (entity_begin == pos) { if (entity_begin == pos) {
cnt--; cnt--;
entity.offset = utf16_pos; entity.offset = utf16_pos;
@ -3010,8 +3010,8 @@ static Result<vector<MessageEntity>> do_parse_html(CSlice text, string &result)
if (tag_name == "a" && attribute_name == Slice("href")) { if (tag_name == "a" && attribute_name == Slice("href")) {
argument = std::move(attribute_value); argument = std::move(attribute_value);
} } else if (tag_name == "code" && attribute_name == Slice("class") &&
if (tag_name == "code" && attribute_name == Slice("class") && begins_with(attribute_value, "language-")) { begins_with(attribute_value, "language-")) {
argument = attribute_value.substr(9); argument = attribute_value.substr(9);
} }
} }
@ -3631,7 +3631,7 @@ static Result<string> clean_input_string_with_entities(const string &text, vecto
utf16_offset += 1 + (c >= 0xf0); // >= 4 bytes in symbol => surrogate pair utf16_offset += 1 + (c >= 0xf0); // >= 4 bytes in symbol => surrogate pair
} }
if (c == 0xe2 && pos + 2 < text_size) { if (c == 0xe2 && pos + 2 < text_size) {
unsigned char next = static_cast<unsigned char>(text[pos + 1]); auto next = static_cast<unsigned char>(text[pos + 1]);
if (next == 0x80) { if (next == 0x80) {
next = static_cast<unsigned char>(text[pos + 2]); next = static_cast<unsigned char>(text[pos + 2]);
if (0xa8 <= next && next <= 0xae) { if (0xa8 <= next && next <= 0xae) {
@ -3642,7 +3642,7 @@ static Result<string> clean_input_string_with_entities(const string &text, vecto
} }
} }
if (c == 0xcc && pos + 1 < text_size) { if (c == 0xcc && pos + 1 < text_size) {
unsigned char next = static_cast<unsigned char>(text[pos + 1]); auto next = static_cast<unsigned char>(text[pos + 1]);
// remove vertical lines // remove vertical lines
if (next == 0xb3 || next == 0xbf || next == 0x8a) { if (next == 0xb3 || next == 0xbf || next == 0x8a) {
pos++; pos++;
@ -4010,7 +4010,7 @@ Status fix_formatted_text(string &text, vector<MessageEntity> &entities, bool al
first_non_whitespaces_pos++; first_non_whitespaces_pos++;
} }
if (first_non_whitespaces_pos > 0) { if (first_non_whitespaces_pos > 0) {
int32 offset = narrow_cast<int32>(first_non_whitespaces_pos); auto offset = narrow_cast<int32>(first_non_whitespaces_pos);
text = result.substr(first_non_whitespaces_pos); text = result.substr(first_non_whitespaces_pos);
for (auto &entity : entities) { for (auto &entity : entities) {
entity.offset -= offset; entity.offset -= offset;

View File

@ -902,8 +902,8 @@ class MessagesDbImpl final : public MessagesDbSyncInterface {
return std::move(right); return std::move(right);
} }
Result<vector<MessagesDbDialogMessage>> get_messages_inner(SqliteStatement &stmt, DialogId dialog_id, static Result<vector<MessagesDbDialogMessage>> get_messages_inner(SqliteStatement &stmt, DialogId dialog_id,
int64 from_message_id, int32 limit) { int64 from_message_id, int32 limit) {
SCOPE_EXIT { SCOPE_EXIT {
stmt.reset(); stmt.reset();
}; };

View File

@ -151,7 +151,7 @@ class UpdateDialogFiltersOrderQuery final : public Td::ResultHandler {
explicit UpdateDialogFiltersOrderQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) { explicit UpdateDialogFiltersOrderQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) {
} }
void send(vector<DialogFilterId> dialog_filter_ids) { void send(const vector<DialogFilterId> &dialog_filter_ids) {
send_query(G()->net_query_creator().create(telegram_api::messages_updateDialogFiltersOrder( send_query(G()->net_query_creator().create(telegram_api::messages_updateDialogFiltersOrder(
transform(dialog_filter_ids, [](auto dialog_filter_id) { return dialog_filter_id.get(); })))); transform(dialog_filter_ids, [](auto dialog_filter_id) { return dialog_filter_id.get(); }))));
} }
@ -496,7 +496,7 @@ class GetChannelMessagesQuery final : public Td::ResultHandler {
} }
} }
} }
td->messages_manager_->on_get_empty_messages(DialogId(channel_id_), std::move(empty_message_ids)); td->messages_manager_->on_get_empty_messages(DialogId(channel_id_), empty_message_ids);
} }
td->messages_manager_->get_channel_difference_if_needed( td->messages_manager_->get_channel_difference_if_needed(
DialogId(channel_id_), std::move(info), DialogId(channel_id_), std::move(info),
@ -1529,7 +1529,7 @@ class SaveDraftMessageQuery final : public Td::ResultHandler {
if (draft_message->input_message_text.disable_web_page_preview) { if (draft_message->input_message_text.disable_web_page_preview) {
flags |= MessagesManager::SEND_MESSAGE_FLAG_DISABLE_WEB_PAGE_PREVIEW; flags |= MessagesManager::SEND_MESSAGE_FLAG_DISABLE_WEB_PAGE_PREVIEW;
} }
if (draft_message->input_message_text.text.entities.size()) { if (!draft_message->input_message_text.text.entities.empty()) {
flags |= MessagesManager::SEND_MESSAGE_FLAG_HAS_ENTITIES; flags |= MessagesManager::SEND_MESSAGE_FLAG_HAS_ENTITIES;
} }
} }
@ -2190,9 +2190,7 @@ class SearchMessagesQuery final : public Td::ResultHandler {
int32 limit, MessageSearchFilter filter, MessageId top_thread_message_id, int64 random_id) { int32 limit, MessageSearchFilter filter, MessageId top_thread_message_id, int64 random_id) {
auto input_peer = dialog_id.is_valid() ? td->messages_manager_->get_input_peer(dialog_id, AccessRights::Read) auto input_peer = dialog_id.is_valid() ? td->messages_manager_->get_input_peer(dialog_id, AccessRights::Read)
: make_tl_object<telegram_api::inputPeerEmpty>(); : make_tl_object<telegram_api::inputPeerEmpty>();
if (input_peer == nullptr) { CHECK(input_peer != nullptr);
return promise_.set_error(Status::Error(400, "Can't access the chat"));
}
dialog_id_ = dialog_id; dialog_id_ = dialog_id;
query_ = query; query_ = query;
@ -6265,8 +6263,6 @@ void MessagesManager::memory_stats(vector<string> &output) {
output.push_back(","); output.push_back(",");
output.push_back("\"message_id_to_dialog_id_\":"); output.push_back(std::to_string(this->message_id_to_dialog_id_.size())); output.push_back("\"message_id_to_dialog_id_\":"); output.push_back(std::to_string(this->message_id_to_dialog_id_.size()));
output.push_back(","); output.push_back(",");
output.push_back("\"message_random_ids_\":"); output.push_back(std::to_string(this->message_random_ids_.size()));
output.push_back(",");
output.push_back("\"notification_group_id_to_dialog_id_\":"); output.push_back(std::to_string(this->notification_group_id_to_dialog_id_.size())); output.push_back("\"notification_group_id_to_dialog_id_\":"); output.push_back(std::to_string(this->notification_group_id_to_dialog_id_.size()));
output.push_back(","); output.push_back(",");
output.push_back("\"previous_repaired_read_inbox_max_message_id_\":"); output.push_back(std::to_string(this->previous_repaired_read_inbox_max_message_id_.size())); output.push_back("\"previous_repaired_read_inbox_max_message_id_\":"); output.push_back(std::to_string(this->previous_repaired_read_inbox_max_message_id_.size()));
@ -9209,9 +9205,9 @@ void MessagesManager::after_get_difference() {
} }
} }
void MessagesManager::on_get_empty_messages(DialogId dialog_id, vector<MessageId> empty_message_ids) { void MessagesManager::on_get_empty_messages(DialogId dialog_id, const vector<MessageId> &empty_message_ids) {
if (!empty_message_ids.empty()) { if (!empty_message_ids.empty()) {
delete_dialog_messages(dialog_id, std::move(empty_message_ids), true, true, "on_get_empty_messages"); delete_dialog_messages(dialog_id, empty_message_ids, true, true, "on_get_empty_messages");
} }
} }
@ -9749,7 +9745,7 @@ void MessagesManager::on_get_dialog_messages_search_result(
CHECK(d != nullptr); CHECK(d != nullptr);
for (auto &message : messages) { for (auto &message : messages) {
auto new_full_message_id = on_get_message(std::move(message), false, dialog_id.get_type() == DialogType::Channel, auto new_full_message_id = on_get_message(std::move(message), false, dialog_id.get_type() == DialogType::Channel,
false, false, false, "SearchMessagesQuery"); false, false, false, "on_get_dialog_messages_search_result");
if (new_full_message_id == FullMessageId()) { if (new_full_message_id == FullMessageId()) {
total_count--; total_count--;
continue; continue;
@ -10232,7 +10228,7 @@ bool MessagesManager::can_get_message_statistics(DialogId dialog_id, const Messa
return td_->contacts_manager_->can_get_channel_message_statistics(dialog_id); return td_->contacts_manager_->can_get_channel_message_statistics(dialog_id);
} }
bool MessagesManager::can_delete_channel_message(DialogParticipantStatus status, const Message *m, bool is_bot) { bool MessagesManager::can_delete_channel_message(const DialogParticipantStatus &status, const Message *m, bool is_bot) {
if (m == nullptr) { if (m == nullptr) {
return true; return true;
} }
@ -16128,14 +16124,13 @@ void MessagesManager::reload_pinned_dialogs(DialogListId dialog_list_id, Promise
if (dialog_list_id.is_folder()) { if (dialog_list_id.is_folder()) {
send_closure(td_->create_net_actor<GetPinnedDialogsActor>(std::move(promise)), &GetPinnedDialogsActor::send, send_closure(td_->create_net_actor<GetPinnedDialogsActor>(std::move(promise)), &GetPinnedDialogsActor::send,
dialog_list_id.get_folder_id(), get_sequence_dispatcher_id(DialogId(), MessageContentType::None)); dialog_list_id.get_folder_id(), get_sequence_dispatcher_id(DialogId(), MessageContentType::None));
} } else if (dialog_list_id.is_filter()) {
if (dialog_list_id.is_filter()) {
schedule_dialog_filters_reload(0.0); schedule_dialog_filters_reload(0.0);
dialog_filter_reload_queries_.push_back(std::move(promise)); dialog_filter_reload_queries_.push_back(std::move(promise));
} }
} }
double MessagesManager::get_dialog_filters_cache_time() const { double MessagesManager::get_dialog_filters_cache_time() {
return DIALOG_FILTERS_CACHE_TIME * 0.0001 * Random::fast(9000, 11000); return DIALOG_FILTERS_CACHE_TIME * 0.0001 * Random::fast(9000, 11000);
} }
@ -16489,7 +16484,7 @@ std::pair<int32, vector<DialogId>> MessagesManager::get_recently_opened_dialogs(
vector<DialogId> MessagesManager::sort_dialogs_by_order(const vector<DialogId> &dialog_ids, int32 limit) const { vector<DialogId> MessagesManager::sort_dialogs_by_order(const vector<DialogId> &dialog_ids, int32 limit) const {
CHECK(!td_->auth_manager_->is_bot()); CHECK(!td_->auth_manager_->is_bot());
int64 fake_order = static_cast<int64>(dialog_ids.size()) + 1; auto fake_order = static_cast<int64>(dialog_ids.size()) + 1;
auto dialog_dates = transform(dialog_ids, [this, &fake_order](DialogId dialog_id) { auto dialog_dates = transform(dialog_ids, [this, &fake_order](DialogId dialog_id) {
const Dialog *d = get_dialog(dialog_id); const Dialog *d = get_dialog(dialog_id);
CHECK(d != nullptr); CHECK(d != nullptr);
@ -16718,7 +16713,7 @@ void MessagesManager::on_get_common_dialogs(UserId user_id, int64 offset_chat_id
td_->contacts_manager_->on_update_user_common_chat_count(user_id, total_count); td_->contacts_manager_->on_update_user_common_chat_count(user_id, total_count);
} }
result.push_back(DialogId()); result.emplace_back();
} }
common_dialogs.total_count = total_count; common_dialogs.total_count = total_count;
} }
@ -17379,15 +17374,15 @@ void MessagesManager::on_get_message_viewers(DialogId dialog_id, vector<UserId>
void MessagesManager::get_dialog_info_full(DialogId dialog_id, Promise<Unit> &&promise, const char *source) { void MessagesManager::get_dialog_info_full(DialogId dialog_id, Promise<Unit> &&promise, const char *source) {
switch (dialog_id.get_type()) { switch (dialog_id.get_type()) {
case DialogType::User: case DialogType::User:
send_closure_later(G()->contacts_manager(), &ContactsManager::load_user_full, dialog_id.get_user_id(), false, send_closure_later(td_->contacts_manager_actor_, &ContactsManager::load_user_full, dialog_id.get_user_id(), false,
std::move(promise), source); std::move(promise), source);
return; return;
case DialogType::Chat: case DialogType::Chat:
send_closure_later(G()->contacts_manager(), &ContactsManager::load_chat_full, dialog_id.get_chat_id(), false, send_closure_later(td_->contacts_manager_actor_, &ContactsManager::load_chat_full, dialog_id.get_chat_id(), false,
std::move(promise), source); std::move(promise), source);
return; return;
case DialogType::Channel: case DialogType::Channel:
send_closure_later(G()->contacts_manager(), &ContactsManager::load_channel_full, dialog_id.get_channel_id(), send_closure_later(td_->contacts_manager_actor_, &ContactsManager::load_channel_full, dialog_id.get_channel_id(),
false, std::move(promise), source); false, std::move(promise), source);
return; return;
case DialogType::SecretChat: case DialogType::SecretChat:
@ -17406,15 +17401,15 @@ void MessagesManager::reload_dialog_info_full(DialogId dialog_id) {
switch (dialog_id.get_type()) { switch (dialog_id.get_type()) {
case DialogType::User: case DialogType::User:
send_closure_later(G()->contacts_manager(), &ContactsManager::reload_user_full, dialog_id.get_user_id()); send_closure_later(td_->contacts_manager_actor_, &ContactsManager::reload_user_full, dialog_id.get_user_id());
return; return;
case DialogType::Chat: case DialogType::Chat:
send_closure_later(G()->contacts_manager(), &ContactsManager::reload_chat_full, dialog_id.get_chat_id(), send_closure_later(td_->contacts_manager_actor_, &ContactsManager::reload_chat_full, dialog_id.get_chat_id(),
Promise<Unit>()); Promise<Unit>());
return; return;
case DialogType::Channel: case DialogType::Channel:
send_closure_later(G()->contacts_manager(), &ContactsManager::reload_channel_full, dialog_id.get_channel_id(), send_closure_later(td_->contacts_manager_actor_, &ContactsManager::reload_channel_full,
Promise<Unit>(), "reload_dialog_info_full"); dialog_id.get_channel_id(), Promise<Unit>(), "reload_dialog_info_full");
return; return;
case DialogType::SecretChat: case DialogType::SecretChat:
return; return;
@ -18259,7 +18254,7 @@ void MessagesManager::reorder_dialog_filters_on_server(vector<DialogFilterId> di
send_closure(actor_id, &MessagesManager::on_reorder_dialog_filters, std::move(dialog_filter_ids), send_closure(actor_id, &MessagesManager::on_reorder_dialog_filters, std::move(dialog_filter_ids),
result.is_error() ? result.move_as_error() : Status::OK()); result.is_error() ? result.move_as_error() : Status::OK());
}); });
td_->create_handler<UpdateDialogFiltersOrderQuery>(std::move(promise))->send(std::move(dialog_filter_ids)); td_->create_handler<UpdateDialogFiltersOrderQuery>(std::move(promise))->send(dialog_filter_ids);
} }
void MessagesManager::on_reorder_dialog_filters(vector<DialogFilterId> dialog_filter_ids, Status result) { void MessagesManager::on_reorder_dialog_filters(vector<DialogFilterId> dialog_filter_ids, Status result) {
@ -19978,7 +19973,7 @@ void MessagesManager::open_dialog(Dialog *d) {
d->is_has_scheduled_database_messages_checked = true; d->is_has_scheduled_database_messages_checked = true;
G()->td_db()->get_messages_db_async()->get_scheduled_messages( G()->td_db()->get_messages_db_async()->get_scheduled_messages(
dialog_id, 1, dialog_id, 1,
PromiseCreator::lambda([dialog_id, actor_id = actor_id(this)](vector<MessagesDbDialogMessage> messages) { PromiseCreator::lambda([actor_id = actor_id(this), dialog_id](vector<MessagesDbDialogMessage> messages) {
if (messages.empty()) { if (messages.empty()) {
send_closure(actor_id, &MessagesManager::set_dialog_has_scheduled_database_messages, dialog_id, false); send_closure(actor_id, &MessagesManager::set_dialog_has_scheduled_database_messages, dialog_id, false);
} }
@ -20712,7 +20707,7 @@ tl_object_ptr<td_api::messages> MessagesManager::get_dialog_history(DialogId dia
} }
} }
if (messages.size()) { if (!messages.empty()) {
// maybe need some messages // maybe need some messages
CHECK(offset == 0); CHECK(offset == 0);
preload_newer_messages(d, MessageId(messages[0]->id_)); preload_newer_messages(d, MessageId(messages[0]->id_));
@ -21238,6 +21233,10 @@ std::pair<int32, vector<MessageId>> MessagesManager::search_dialog_messages(
promise.set_error(Status::Error(400, "Chat not found")); promise.set_error(Status::Error(400, "Chat not found"));
return result; return result;
} }
if (!have_input_peer(dialog_id, AccessRights::Read)) {
promise.set_error(Status::Error(400, "Can't access the chat"));
return {};
}
DialogId sender_dialog_id; DialogId sender_dialog_id;
if (sender != nullptr) { if (sender != nullptr) {
@ -21895,7 +21894,7 @@ void MessagesManager::on_search_dialog_messages_db_result(int64 random_id, Dialo
} }
auto &message_count = d->message_count_by_index[message_search_filter_index(filter)]; auto &message_count = d->message_count_by_index[message_search_filter_index(filter)];
int32 result_size = narrow_cast<int32>(res.size()); auto result_size = narrow_cast<int32>(res.size());
bool from_the_end = bool from_the_end =
from_message_id == MessageId::max() || (offset < 0 && (result_size == 0 || res[0] < from_message_id)); from_message_id == MessageId::max() || (offset < 0 && (result_size == 0 || res[0] < from_message_id));
if ((message_count != -1 && message_count < result_size) || if ((message_count != -1 && message_count < result_size) ||
@ -21939,7 +21938,7 @@ td_api::object_ptr<td_api::foundMessages> MessagesManager::get_found_messages_ob
} }
MessagesManager::FoundMessages MessagesManager::offline_search_messages(DialogId dialog_id, const string &query, MessagesManager::FoundMessages MessagesManager::offline_search_messages(DialogId dialog_id, const string &query,
const string &offset, int32 limit, string offset, int32 limit,
MessageSearchFilter filter, int64 &random_id, MessageSearchFilter filter, int64 &random_id,
Promise<> &&promise) { Promise<> &&promise) {
if (!G()->parameters().use_message_db) { if (!G()->parameters().use_message_db) {
@ -21993,8 +21992,9 @@ MessagesManager::FoundMessages MessagesManager::offline_search_messages(DialogId
found_fts_messages_[random_id]; // reserve place for result found_fts_messages_[random_id]; // reserve place for result
G()->td_db()->get_messages_db_async()->get_messages_fts( G()->td_db()->get_messages_db_async()->get_messages_fts(
std::move(fts_query), PromiseCreator::lambda([random_id, offset, limit, promise = std::move(promise)]( std::move(fts_query),
Result<MessagesDbFtsResult> fts_result) mutable { PromiseCreator::lambda([random_id, offset = std::move(offset), limit,
promise = std::move(promise)](Result<MessagesDbFtsResult> fts_result) mutable {
send_closure(G()->messages_manager(), &MessagesManager::on_messages_db_fts_result, std::move(fts_result), send_closure(G()->messages_manager(), &MessagesManager::on_messages_db_fts_result, std::move(fts_result),
std::move(offset), limit, random_id, std::move(promise)); std::move(offset), limit, random_id, std::move(promise));
})); }));
@ -22021,7 +22021,7 @@ void MessagesManager::on_messages_db_fts_result(Result<MessagesDbFtsResult> resu
for (auto &message : fts_result.messages) { for (auto &message : fts_result.messages) {
auto m = on_get_message_from_database(message, false, "on_messages_db_fts_result"); auto m = on_get_message_from_database(message, false, "on_messages_db_fts_result");
if (m != nullptr) { if (m != nullptr) {
res.push_back(FullMessageId(message.dialog_id, m->message_id)); res.emplace_back(message.dialog_id, m->message_id);
} }
} }
@ -22055,7 +22055,7 @@ void MessagesManager::on_messages_db_calls_result(Result<MessagesDbCallsResult>
auto m = on_get_message_from_database(message, false, "on_messages_db_calls_result"); auto m = on_get_message_from_database(message, false, "on_messages_db_calls_result");
if (m != nullptr && first_db_message_id <= m->message_id) { if (m != nullptr && first_db_message_id <= m->message_id) {
res.push_back(FullMessageId(message.dialog_id, m->message_id)); res.emplace_back(message.dialog_id, m->message_id);
} }
} }
it->second.first = calls_db_state_.message_count_by_index[call_message_search_filter_index(filter)]; it->second.first = calls_db_state_.message_count_by_index[call_message_search_filter_index(filter)];
@ -23249,6 +23249,14 @@ bool MessagesManager::is_anonymous_administrator(DialogId dialog_id, string *aut
return true; return true;
} }
int64 MessagesManager::generate_new_random_id() {
int64 random_id;
do {
random_id = Random::secure_int64();
} while (random_id == 0 || being_sent_messages_.find(random_id) != being_sent_messages_.end());
return random_id;
}
unique_ptr<MessagesManager::Message> MessagesManager::create_message_to_send( unique_ptr<MessagesManager::Message> MessagesManager::create_message_to_send(
Dialog *d, MessageId top_thread_message_id, MessageId reply_to_message_id, const MessageSendOptions &options, Dialog *d, MessageId top_thread_message_id, MessageId reply_to_message_id, const MessageSendOptions &options,
unique_ptr<MessageContent> &&content, bool suppress_reply_info, unique_ptr<MessageForwardInfo> forward_info, unique_ptr<MessageContent> &&content, bool suppress_reply_info, unique_ptr<MessageForwardInfo> forward_info,
@ -23324,7 +23332,7 @@ unique_ptr<MessagesManager::Message> MessagesManager::create_message_to_send(
} }
m->content = std::move(content); m->content = std::move(content);
m->forward_info = std::move(forward_info); m->forward_info = std::move(forward_info);
m->is_copy = is_copy || forward_info != nullptr; m->is_copy = is_copy || m->forward_info != nullptr;
if (td_->auth_manager_->is_bot() || options.disable_notification || if (td_->auth_manager_->is_bot() || options.disable_notification ||
G()->shared_config().get_option_boolean("ignore_default_disable_notification")) { G()->shared_config().get_option_boolean("ignore_default_disable_notification")) {
@ -23369,10 +23377,7 @@ MessagesManager::Message *MessagesManager::get_message_to_send(
message->have_previous = true; message->have_previous = true;
message->have_next = true; message->have_next = true;
do { message->random_id = generate_new_random_id();
message->random_id = Random::secure_int64();
} while (message->random_id == 0 || message_random_ids_.find(message->random_id) != message_random_ids_.end());
message_random_ids_.insert(message->random_id);
bool need_update = false; bool need_update = false;
CHECK(have_input_peer(d->dialog_id, AccessRights::Read)); CHECK(have_input_peer(d->dialog_id, AccessRights::Read));
@ -23423,7 +23428,7 @@ Status MessagesManager::can_send_message(DialogId dialog_id) const {
return Status::OK(); return Status::OK();
} }
MessageId MessagesManager::get_persistent_message_id(const Dialog *d, MessageId message_id) const { MessageId MessagesManager::get_persistent_message_id(const Dialog *d, MessageId message_id) {
if (!message_id.is_valid() && !message_id.is_valid_scheduled()) { if (!message_id.is_valid() && !message_id.is_valid_scheduled()) {
return MessageId(); return MessageId();
} }
@ -25788,18 +25793,14 @@ void MessagesManager::update_message_max_reply_media_timestamp(const Dialog *d,
return; return;
} }
auto new_max_reply_media_timestamp = m->max_reply_media_timestamp; auto new_max_reply_media_timestamp = -1;
if (!m->reply_to_message_id.is_valid()) { if (m->reply_to_message_id.is_valid()) {
new_max_reply_media_timestamp = -1;
} else {
auto replied_m = get_message(d, m->reply_to_message_id); auto replied_m = get_message(d, m->reply_to_message_id);
if (replied_m != nullptr) { if (replied_m != nullptr) {
new_max_reply_media_timestamp = get_message_own_max_media_timestamp(replied_m); new_max_reply_media_timestamp = get_message_own_max_media_timestamp(replied_m);
} else if (d->deleted_message_ids.count(m->reply_to_message_id) || } else if (!d->deleted_message_ids.count(m->reply_to_message_id) &&
m->reply_to_message_id <= d->last_clear_history_message_id || m->reply_to_message_id > d->last_clear_history_message_id &&
m->reply_to_message_id <= d->max_unavailable_message_id) { m->reply_to_message_id > d->max_unavailable_message_id) {
new_max_reply_media_timestamp = -1;
} else {
// replied message isn't deleted and isn't loaded yet // replied message isn't deleted and isn't loaded yet
return; return;
} }
@ -28988,7 +28989,7 @@ void MessagesManager::send_update_chat_has_scheduled_messages(Dialog *d, bool fr
} }
void MessagesManager::send_update_user_chat_action(DialogId dialog_id, MessageId top_thread_message_id, UserId user_id, void MessagesManager::send_update_user_chat_action(DialogId dialog_id, MessageId top_thread_message_id, UserId user_id,
DialogAction action) { const DialogAction &action) {
if (td_->auth_manager_->is_bot()) { if (td_->auth_manager_->is_bot()) {
return; return;
} }
@ -29189,10 +29190,7 @@ void MessagesManager::on_send_message_file_part_missing(int64 random_id, int bad
CHECK(d != nullptr); CHECK(d != nullptr);
// need to change message random_id before resending // need to change message random_id before resending
do { m->random_id = generate_new_random_id();
m->random_id = Random::secure_int64();
} while (m->random_id == 0 || message_random_ids_.find(m->random_id) != message_random_ids_.end());
message_random_ids_.insert(m->random_id);
delete_random_id_to_message_id_correspondence(d, random_id, m->message_id); delete_random_id_to_message_id_correspondence(d, random_id, m->message_id);
add_random_id_to_message_id_correspondence(d, m->random_id, m->message_id); add_random_id_to_message_id_correspondence(d, m->random_id, m->message_id);
@ -29241,10 +29239,7 @@ void MessagesManager::on_send_message_file_reference_error(int64 random_id) {
CHECK(d != nullptr); CHECK(d != nullptr);
// need to change message random_id before resending // need to change message random_id before resending
do { m->random_id = generate_new_random_id();
m->random_id = Random::secure_int64();
} while (m->random_id == 0 || message_random_ids_.find(m->random_id) != message_random_ids_.end());
message_random_ids_.insert(m->random_id);
delete_random_id_to_message_id_correspondence(d, random_id, m->message_id); delete_random_id_to_message_id_correspondence(d, random_id, m->message_id);
add_random_id_to_message_id_correspondence(d, m->random_id, m->message_id); add_random_id_to_message_id_correspondence(d, m->random_id, m->message_id);
@ -32037,7 +32032,7 @@ tl_object_ptr<td_api::ChatEventAction> MessagesManager::get_chat_event_action_ob
} }
case telegram_api::channelAdminLogEventActionParticipantMute::ID: { case telegram_api::channelAdminLogEventActionParticipantMute::ID: {
auto action = move_tl_object_as<telegram_api::channelAdminLogEventActionParticipantMute>(action_ptr); auto action = move_tl_object_as<telegram_api::channelAdminLogEventActionParticipantMute>(action_ptr);
GroupCallParticipant participant(std::move(action->participant_), 0); GroupCallParticipant participant(action->participant_, 0);
if (!participant.is_valid()) { if (!participant.is_valid()) {
return nullptr; return nullptr;
} }
@ -32046,7 +32041,7 @@ tl_object_ptr<td_api::ChatEventAction> MessagesManager::get_chat_event_action_ob
} }
case telegram_api::channelAdminLogEventActionParticipantUnmute::ID: { case telegram_api::channelAdminLogEventActionParticipantUnmute::ID: {
auto action = move_tl_object_as<telegram_api::channelAdminLogEventActionParticipantUnmute>(action_ptr); auto action = move_tl_object_as<telegram_api::channelAdminLogEventActionParticipantUnmute>(action_ptr);
GroupCallParticipant participant(std::move(action->participant_), 0); GroupCallParticipant participant(action->participant_, 0);
if (!participant.is_valid()) { if (!participant.is_valid()) {
return nullptr; return nullptr;
} }
@ -32055,7 +32050,7 @@ tl_object_ptr<td_api::ChatEventAction> MessagesManager::get_chat_event_action_ob
} }
case telegram_api::channelAdminLogEventActionParticipantVolume::ID: { case telegram_api::channelAdminLogEventActionParticipantVolume::ID: {
auto action = move_tl_object_as<telegram_api::channelAdminLogEventActionParticipantVolume>(action_ptr); auto action = move_tl_object_as<telegram_api::channelAdminLogEventActionParticipantVolume>(action_ptr);
GroupCallParticipant participant(std::move(action->participant_), 0); GroupCallParticipant participant(action->participant_, 0);
if (!participant.is_valid()) { if (!participant.is_valid()) {
return nullptr; return nullptr;
} }
@ -33580,10 +33575,6 @@ void MessagesManager::delete_message_from_database(Dialog *d, MessageId message_
} }
} }
if (m != nullptr && m->random_id != 0 && (m->is_outgoing || d->dialog_id == get_my_dialog_id())) {
message_random_ids_.erase(m->random_id);
}
if (m != nullptr && m->notification_id.is_valid()) { if (m != nullptr && m->notification_id.is_valid()) {
CHECK(!message_id.is_scheduled()); CHECK(!message_id.is_scheduled());
auto from_mentions = is_from_mention_notification_group(d, m); auto from_mentions = is_from_mention_notification_group(d, m);
@ -35565,7 +35556,7 @@ unique_ptr<MessagesManager::Dialog> MessagesManager::parse_dialog(DialogId dialo
return d; return d;
} }
MessagesManager::Dialog *MessagesManager::on_load_dialog_from_database(DialogId dialog_id, const BufferSlice &value, MessagesManager::Dialog *MessagesManager::on_load_dialog_from_database(DialogId dialog_id, BufferSlice &&value,
const char *source) { const char *source) {
CHECK(G()->parameters().use_message_db); CHECK(G()->parameters().use_message_db);
@ -35664,17 +35655,17 @@ bool MessagesManager::has_dialogs_from_folder(const DialogList &list, const Dial
return false; return false;
} }
bool MessagesManager::is_dialog_in_list(const Dialog *d, DialogListId dialog_list_id) const { bool MessagesManager::is_dialog_in_list(const Dialog *d, DialogListId dialog_list_id) {
return td::contains(d->dialog_list_ids, dialog_list_id); return td::contains(d->dialog_list_ids, dialog_list_id);
} }
void MessagesManager::add_dialog_to_list(Dialog *d, DialogListId dialog_list_id) const { void MessagesManager::add_dialog_to_list(Dialog *d, DialogListId dialog_list_id) {
LOG(INFO) << "Add " << d->dialog_id << " to " << dialog_list_id; LOG(INFO) << "Add " << d->dialog_id << " to " << dialog_list_id;
CHECK(!is_dialog_in_list(d, dialog_list_id)); CHECK(!is_dialog_in_list(d, dialog_list_id));
d->dialog_list_ids.push_back(dialog_list_id); d->dialog_list_ids.push_back(dialog_list_id);
} }
void MessagesManager::remove_dialog_from_list(Dialog *d, DialogListId dialog_list_id) const { void MessagesManager::remove_dialog_from_list(Dialog *d, DialogListId dialog_list_id) {
LOG(INFO) << "Remove " << d->dialog_id << " from " << dialog_list_id; LOG(INFO) << "Remove " << d->dialog_id << " from " << dialog_list_id;
bool is_removed = td::remove(d->dialog_list_ids, dialog_list_id); bool is_removed = td::remove(d->dialog_list_ids, dialog_list_id);
CHECK(is_removed); CHECK(is_removed);
@ -35811,7 +35802,7 @@ MessagesManager::get_dialog_positions(const Dialog *d) const {
return positions; return positions;
} }
vector<DialogListId> MessagesManager::get_dialog_list_ids(const Dialog *d) const { vector<DialogListId> MessagesManager::get_dialog_list_ids(const Dialog *d) {
return d->dialog_list_ids; return d->dialog_list_ids;
} }
@ -36957,8 +36948,6 @@ MessagesManager::Message *MessagesManager::continue_send_message(DialogId dialog
m->have_previous = true; m->have_previous = true;
m->have_next = true; m->have_next = true;
message_random_ids_.insert(m->random_id);
bool need_update = false; bool need_update = false;
bool need_update_dialog_pos = false; bool need_update_dialog_pos = false;
auto result_message = auto result_message =
@ -37182,7 +37171,6 @@ void MessagesManager::on_binlog_events(vector<BinlogEvent> &&events) {
m->have_previous = true; m->have_previous = true;
m->have_next = true; m->have_next = true;
message_random_ids_.insert(m->random_id);
forwarded_messages.push_back(add_message_to_dialog(to_dialog, std::move(m), true, &need_update, forwarded_messages.push_back(add_message_to_dialog(to_dialog, std::move(m), true, &need_update,
&need_update_dialog_pos, "forward message again")); &need_update_dialog_pos, "forward message again"));
send_update_new_message(to_dialog, forwarded_messages.back()); send_update_new_message(to_dialog, forwarded_messages.back());

View File

@ -182,7 +182,7 @@ class MessagesManager final : public Actor {
bool have_input_peer(DialogId dialog_id, AccessRights access_rights) const; bool have_input_peer(DialogId dialog_id, AccessRights access_rights) const;
void on_get_empty_messages(DialogId dialog_id, vector<MessageId> empty_message_ids); void on_get_empty_messages(DialogId dialog_id, const vector<MessageId> &empty_message_ids);
struct MessagesInfo { struct MessagesInfo {
vector<tl_object_ptr<telegram_api::Message>> messages; vector<tl_object_ptr<telegram_api::Message>> messages;
@ -522,7 +522,7 @@ class MessagesManager final : public Actor {
void load_dialogs(vector<DialogId> dialog_ids, Promise<vector<DialogId>> &&promise); void load_dialogs(vector<DialogId> dialog_ids, Promise<vector<DialogId>> &&promise);
void load_dialog_filter(DialogFilterId dialog_id, bool force, Promise<Unit> &&promise); void load_dialog_filter(DialogFilterId dialog_filter_id, bool force, Promise<Unit> &&promise);
void get_recommended_dialog_filters(Promise<td_api::object_ptr<td_api::recommendedChatFilters>> &&promise); void get_recommended_dialog_filters(Promise<td_api::object_ptr<td_api::recommendedChatFilters>> &&promise);
@ -707,7 +707,7 @@ class MessagesManager final : public Actor {
td_api::object_ptr<td_api::foundMessages> get_found_messages_object(const FoundMessages &found_messages, td_api::object_ptr<td_api::foundMessages> get_found_messages_object(const FoundMessages &found_messages,
const char *source); const char *source);
FoundMessages offline_search_messages(DialogId dialog_id, const string &query, const string &offset, int32 limit, FoundMessages offline_search_messages(DialogId dialog_id, const string &query, string offset, int32 limit,
MessageSearchFilter filter, int64 &random_id, Promise<> &&promise); MessageSearchFilter filter, int64 &random_id, Promise<> &&promise);
std::pair<int32, vector<FullMessageId>> search_messages(FolderId folder_id, bool ignore_folder_id, std::pair<int32, vector<FullMessageId>> search_messages(FolderId folder_id, bool ignore_folder_id,
@ -986,7 +986,7 @@ class MessagesManager final : public Actor {
, sender_name(std::move(sender_name)) , sender_name(std::move(sender_name))
, from_dialog_id(from_dialog_id) , from_dialog_id(from_dialog_id)
, from_message_id(from_message_id) , from_message_id(from_message_id)
, psa_type(psa_type) , psa_type(std::move(psa_type))
, is_imported(is_imported) { , is_imported(is_imported) {
} }
@ -1162,8 +1162,8 @@ class MessagesManager final : public Actor {
int32 server_unread_count = 0; int32 server_unread_count = 0;
int32 local_unread_count = 0; int32 local_unread_count = 0;
int32 unread_mention_count = 0; int32 unread_mention_count = 0;
MessageId last_read_inbox_message_id;
int32 last_read_inbox_message_date = 0; // secret chats only int32 last_read_inbox_message_date = 0; // secret chats only
MessageId last_read_inbox_message_id;
MessageId last_read_outbox_message_id; MessageId last_read_outbox_message_id;
MessageId last_pinned_message_id; MessageId last_pinned_message_id;
MessageId reply_markup_message_id; MessageId reply_markup_message_id;
@ -1188,11 +1188,13 @@ class MessagesManager final : public Actor {
MessageId MessageId
max_unavailable_message_id; // maximum unavailable message identifier for dialogs with cleared/unavailable history max_unavailable_message_id; // maximum unavailable message identifier for dialogs with cleared/unavailable history
int32 distance = -1; // distance to the peer
int32 last_clear_history_date = 0; int32 last_clear_history_date = 0;
MessageId last_clear_history_message_id; MessageId last_clear_history_message_id;
int64 order = DEFAULT_ORDER; int64 order = DEFAULT_ORDER;
int32 delete_last_message_date = 0;
MessageId deleted_last_message_id; MessageId deleted_last_message_id;
int32 delete_last_message_date = 0;
int32 pending_last_message_date = 0; int32 pending_last_message_date = 0;
MessageId pending_last_message_id; MessageId pending_last_message_id;
MessageId max_notification_message_id; MessageId max_notification_message_id;
@ -1211,8 +1213,6 @@ class MessagesManager final : public Actor {
NotificationId new_secret_chat_notification_id; // secret chats only NotificationId new_secret_chat_notification_id; // secret chats only
MessageId pinned_message_notification_message_id; MessageId pinned_message_notification_message_id;
int32 distance = -1; // distance to the peer
bool has_contact_registered_message = false; bool has_contact_registered_message = false;
bool is_last_message_deleted_locally = false; bool is_last_message_deleted_locally = false;
@ -1266,10 +1266,13 @@ class MessagesManager final : public Actor {
bool has_unload_timeout = false; bool has_unload_timeout = false;
bool is_channel_difference_finished = false; bool is_channel_difference_finished = false;
bool suffix_load_done_ = false;
bool suffix_load_has_query_ = false;
int32 pts = 0; // for channels only int32 pts = 0; // for channels only
int32 pending_read_channel_inbox_pts = 0; // for channels only int32 pending_read_channel_inbox_pts = 0; // for channels only
MessageId pending_read_channel_inbox_max_message_id; // for channels only
int32 pending_read_channel_inbox_server_unread_count = 0; // for channels only int32 pending_read_channel_inbox_server_unread_count = 0; // for channels only
MessageId pending_read_channel_inbox_max_message_id; // for channels only
std::unordered_map<int64, MessageId> random_id_to_message_id; // for secret chats only std::unordered_map<int64, MessageId> random_id_to_message_id; // for secret chats only
MessageId last_assigned_message_id; // identifier of the last local or yet unsent message, assigned after MessageId last_assigned_message_id; // identifier of the last local or yet unsent message, assigned after
@ -1300,8 +1303,6 @@ class MessagesManager final : public Actor {
// [suffix_load_first_message_id_, last_message_id] are loaded // [suffix_load_first_message_id_, last_message_id] are loaded
MessageId suffix_load_query_message_id_; MessageId suffix_load_query_message_id_;
std::vector<std::pair<Promise<>, std::function<bool(const Message *)>>> suffix_load_queries_; std::vector<std::pair<Promise<>, std::function<bool(const Message *)>>> suffix_load_queries_;
bool suffix_load_done_ = false;
bool suffix_load_has_query_ = false;
std::unordered_map<MessageId, int64, MessageIdHash> pending_viewed_live_locations; // message_id -> task_id std::unordered_map<MessageId, int64, MessageIdHash> pending_viewed_live_locations; // message_id -> task_id
std::unordered_set<MessageId, MessageIdHash> pending_viewed_message_ids; std::unordered_set<MessageId, MessageIdHash> pending_viewed_message_ids;
@ -1781,6 +1782,8 @@ class MessagesManager final : public Actor {
bool is_anonymous_administrator(DialogId dialog_id, string *author_signature) const; bool is_anonymous_administrator(DialogId dialog_id, string *author_signature) const;
int64 generate_new_random_id();
unique_ptr<Message> create_message_to_send(Dialog *d, MessageId top_thread_message_id, MessageId reply_to_message_id, unique_ptr<Message> create_message_to_send(Dialog *d, MessageId top_thread_message_id, MessageId reply_to_message_id,
const MessageSendOptions &options, unique_ptr<MessageContent> &&content, const MessageSendOptions &options, unique_ptr<MessageContent> &&content,
bool suppress_reply_info, unique_ptr<MessageForwardInfo> forward_info, bool suppress_reply_info, unique_ptr<MessageForwardInfo> forward_info,
@ -1817,7 +1820,7 @@ class MessagesManager final : public Actor {
bool was_uploaded, bool was_thumbnail_uploaded, string file_reference, bool was_uploaded, bool was_thumbnail_uploaded, string file_reference,
int32 scheduled_date, uint64 generation, Result<int32> &&result); int32 scheduled_date, uint64 generation, Result<int32> &&result);
MessageId get_persistent_message_id(const Dialog *d, MessageId message_id) const; static MessageId get_persistent_message_id(const Dialog *d, MessageId message_id);
static FullMessageId get_replied_message_id(DialogId dialog_id, const Message *m); static FullMessageId get_replied_message_id(DialogId dialog_id, const Message *m);
@ -1916,18 +1919,18 @@ class MessagesManager final : public Actor {
void on_yet_unsent_media_queue_updated(DialogId dialog_id); void on_yet_unsent_media_queue_updated(DialogId dialog_id);
void save_send_bot_start_message_log_event(UserId bot_user_id, DialogId dialog_id, const string &parameter, static void save_send_bot_start_message_log_event(UserId bot_user_id, DialogId dialog_id, const string &parameter,
const Message *m); const Message *m);
void do_send_bot_start_message(UserId bot_user_id, DialogId dialog_id, const string &parameter, const Message *m); void do_send_bot_start_message(UserId bot_user_id, DialogId dialog_id, const string &parameter, const Message *m);
void save_send_inline_query_result_message_log_event(DialogId dialog_id, const Message *m, int64 query_id, static void save_send_inline_query_result_message_log_event(DialogId dialog_id, const Message *m, int64 query_id,
const string &result_id); const string &result_id);
void do_send_inline_query_result_message(DialogId dialog_id, const Message *m, int64 query_id, void do_send_inline_query_result_message(DialogId dialog_id, const Message *m, int64 query_id,
const string &result_id); const string &result_id);
uint64 save_send_screenshot_taken_notification_message_log_event(DialogId dialog_id, const Message *m); static uint64 save_send_screenshot_taken_notification_message_log_event(DialogId dialog_id, const Message *m);
void do_send_screenshot_taken_notification_message(DialogId dialog_id, const Message *m, uint64 log_event_id); void do_send_screenshot_taken_notification_message(DialogId dialog_id, const Message *m, uint64 log_event_id);
@ -1941,7 +1944,7 @@ class MessagesManager final : public Actor {
bool can_get_message_statistics(DialogId dialog_id, const Message *m) const; bool can_get_message_statistics(DialogId dialog_id, const Message *m) const;
static bool can_delete_channel_message(DialogParticipantStatus status, const Message *m, bool is_bot); static bool can_delete_channel_message(const DialogParticipantStatus &status, const Message *m, bool is_bot);
bool can_delete_message(DialogId dialog_id, const Message *m) const; bool can_delete_message(DialogId dialog_id, const Message *m) const;
@ -2123,7 +2126,7 @@ class MessagesManager final : public Actor {
void on_dialog_updated(DialogId dialog_id, const char *source); void on_dialog_updated(DialogId dialog_id, const char *source);
BufferSlice get_dialog_database_value(const Dialog *d); static BufferSlice get_dialog_database_value(const Dialog *d);
void save_dialog_to_database(DialogId dialog_id); void save_dialog_to_database(DialogId dialog_id);
@ -2206,9 +2209,9 @@ class MessagesManager final : public Actor {
void do_delete_message_log_event(const DeleteMessageLogEvent &log_event) const; void do_delete_message_log_event(const DeleteMessageLogEvent &log_event) const;
void attach_message_to_previous(Dialog *d, MessageId message_id, const char *source); static void attach_message_to_previous(Dialog *d, MessageId message_id, const char *source);
void attach_message_to_next(Dialog *d, MessageId message_id, const char *source); static void attach_message_to_next(Dialog *d, MessageId message_id, const char *source);
bool update_message(Dialog *d, Message *old_message, unique_ptr<Message> new_message, bool *need_update_dialog_pos, bool update_message(Dialog *d, Message *old_message, unique_ptr<Message> new_message, bool *need_update_dialog_pos,
bool is_message_in_dialog); bool is_message_in_dialog);
@ -2247,7 +2250,7 @@ class MessagesManager final : public Actor {
vector<Notification> get_message_notifications_from_database_force(Dialog *d, bool from_mentions, int32 limit); vector<Notification> get_message_notifications_from_database_force(Dialog *d, bool from_mentions, int32 limit);
Result<vector<MessagesDbDialogMessage>> do_get_message_notifications_from_database_force( static Result<vector<MessagesDbDialogMessage>> do_get_message_notifications_from_database_force(
Dialog *d, bool from_mentions, NotificationId from_notification_id, MessageId from_message_id, int32 limit); Dialog *d, bool from_mentions, NotificationId from_notification_id, MessageId from_message_id, int32 limit);
void do_get_message_notifications_from_database(Dialog *d, bool from_mentions, void do_get_message_notifications_from_database(Dialog *d, bool from_mentions,
@ -2341,7 +2344,7 @@ class MessagesManager final : public Actor {
void send_update_chat_has_scheduled_messages(Dialog *d, bool from_deletion); void send_update_chat_has_scheduled_messages(Dialog *d, bool from_deletion);
void send_update_user_chat_action(DialogId dialog_id, MessageId top_thread_message_id, UserId user_id, void send_update_user_chat_action(DialogId dialog_id, MessageId top_thread_message_id, UserId user_id,
DialogAction action); const DialogAction &action);
void repair_dialog_action_bar(Dialog *d, const char *source); void repair_dialog_action_bar(Dialog *d, const char *source);
@ -2387,7 +2390,7 @@ class MessagesManager final : public Actor {
td_api::object_ptr<td_api::updateUnreadChatCount> get_update_unread_chat_count_object(const DialogList &list) const; td_api::object_ptr<td_api::updateUnreadChatCount> get_update_unread_chat_count_object(const DialogList &list) const;
void save_unread_chat_count(const DialogList &list); static void save_unread_chat_count(const DialogList &list);
void set_dialog_last_read_inbox_message_id(Dialog *d, MessageId message_id, int32 server_unread_count, void set_dialog_last_read_inbox_message_id(Dialog *d, MessageId message_id, int32 server_unread_count,
int32 local_unread_count, bool force_update, const char *source); int32 local_unread_count, bool force_update, const char *source);
@ -2468,7 +2471,8 @@ class MessagesManager final : public Actor {
static string get_notification_settings_scope_database_key(NotificationSettingsScope scope); static string get_notification_settings_scope_database_key(NotificationSettingsScope scope);
void save_scope_notification_settings(NotificationSettingsScope scope, const ScopeNotificationSettings &new_settings); static void save_scope_notification_settings(NotificationSettingsScope scope,
const ScopeNotificationSettings &new_settings);
bool update_dialog_notification_settings(DialogId dialog_id, DialogNotificationSettings *current_settings, bool update_dialog_notification_settings(DialogId dialog_id, DialogNotificationSettings *current_settings,
const DialogNotificationSettings &new_settings); const DialogNotificationSettings &new_settings);
@ -2533,7 +2537,7 @@ class MessagesManager final : public Actor {
Dialog *get_dialog_force(DialogId dialog_id, const char *source = "get_dialog_force"); Dialog *get_dialog_force(DialogId dialog_id, const char *source = "get_dialog_force");
Dialog *on_load_dialog_from_database(DialogId dialog_id, const BufferSlice &value, const char *source); Dialog *on_load_dialog_from_database(DialogId dialog_id, BufferSlice &&value, const char *source);
void on_get_dialogs_from_database(FolderId folder_id, int32 limit, DialogDbGetDialogsResult &&dialogs, void on_get_dialogs_from_database(FolderId folder_id, int32 limit, DialogDbGetDialogsResult &&dialogs,
Promise<Unit> &&promise); Promise<Unit> &&promise);
@ -2546,7 +2550,7 @@ class MessagesManager final : public Actor {
void reload_pinned_dialogs(DialogListId dialog_list_id, Promise<Unit> &&promise); void reload_pinned_dialogs(DialogListId dialog_list_id, Promise<Unit> &&promise);
double get_dialog_filters_cache_time() const; static double get_dialog_filters_cache_time();
void schedule_dialog_filters_reload(double timeout); void schedule_dialog_filters_reload(double timeout);
@ -2616,11 +2620,11 @@ class MessagesManager final : public Actor {
bool has_dialogs_from_folder(const DialogList &list, const DialogFolder &folder) const; bool has_dialogs_from_folder(const DialogList &list, const DialogFolder &folder) const;
bool is_dialog_in_list(const Dialog *d, DialogListId dialog_list_id) const; static bool is_dialog_in_list(const Dialog *d, DialogListId dialog_list_id);
void add_dialog_to_list(Dialog *d, DialogListId dialog_list_id) const; static void add_dialog_to_list(Dialog *d, DialogListId dialog_list_id);
void remove_dialog_from_list(Dialog *d, DialogListId dialog_list_id) const; static void remove_dialog_from_list(Dialog *d, DialogListId dialog_list_id);
bool need_dialog_in_filter(const Dialog *d, const DialogFilter *filter) const; bool need_dialog_in_filter(const Dialog *d, const DialogFilter *filter) const;
@ -2633,7 +2637,8 @@ class MessagesManager final : public Actor {
std::unordered_map<DialogListId, DialogPositionInList, DialogListIdHash> get_dialog_positions(const Dialog *d) const; std::unordered_map<DialogListId, DialogPositionInList, DialogListIdHash> get_dialog_positions(const Dialog *d) const;
vector<DialogListId> get_dialog_list_ids(const Dialog *d) const; static vector<DialogListId> get_dialog_list_ids(const Dialog *d);
DialogListView get_dialog_lists(const Dialog *d); DialogListView get_dialog_lists(const Dialog *d);
DialogList &add_dialog_list(DialogListId dialog_list_id); DialogList &add_dialog_list(DialogListId dialog_list_id);
@ -3033,50 +3038,54 @@ class MessagesManager final : public Actor {
static void add_message_dependencies(Dependencies &dependencies, const Message *m); static void add_message_dependencies(Dependencies &dependencies, const Message *m);
void save_send_message_log_event(DialogId dialog_id, const Message *m); static void save_send_message_log_event(DialogId dialog_id, const Message *m);
uint64 save_toggle_dialog_report_spam_state_on_server_log_event(DialogId dialog_id, bool is_spam_dialog); static uint64 save_toggle_dialog_report_spam_state_on_server_log_event(DialogId dialog_id, bool is_spam_dialog);
uint64 save_delete_messages_from_server_log_event(DialogId dialog_id, const vector<MessageId> &message_ids, static uint64 save_delete_messages_from_server_log_event(DialogId dialog_id, const vector<MessageId> &message_ids,
bool revoke); bool revoke);
uint64 save_delete_scheduled_messages_from_server_log_event(DialogId dialog_id, const vector<MessageId> &message_ids); static uint64 save_delete_scheduled_messages_from_server_log_event(DialogId dialog_id,
const vector<MessageId> &message_ids);
uint64 save_delete_dialog_history_from_server_log_event(DialogId dialog_id, MessageId max_message_id, static uint64 save_delete_dialog_history_from_server_log_event(DialogId dialog_id, MessageId max_message_id,
bool remove_from_dialog_list, bool revoke); bool remove_from_dialog_list, bool revoke);
uint64 save_delete_all_call_messages_from_server_log_event(bool revoke); static uint64 save_delete_all_call_messages_from_server_log_event(bool revoke);
uint64 save_block_message_sender_from_replies_on_server_log_event(MessageId message_id, bool delete_message, static uint64 save_block_message_sender_from_replies_on_server_log_event(MessageId message_id, bool delete_message,
bool delete_all_messages, bool report_spam); bool delete_all_messages, bool report_spam);
uint64 save_delete_all_channel_messages_from_user_on_server_log_event(ChannelId channel_id, UserId user_id); static uint64 save_delete_all_channel_messages_from_user_on_server_log_event(ChannelId channel_id, UserId user_id);
uint64 save_read_all_dialog_mentions_on_server_log_event(DialogId dialog_id); static uint64 save_read_all_dialog_mentions_on_server_log_event(DialogId dialog_id);
uint64 save_toggle_dialog_is_pinned_on_server_log_event(DialogId dialog_id, bool is_pinned); static uint64 save_toggle_dialog_is_pinned_on_server_log_event(DialogId dialog_id, bool is_pinned);
uint64 save_reorder_pinned_dialogs_on_server_log_event(FolderId folder_id, const vector<DialogId> &dialog_ids); static uint64 save_reorder_pinned_dialogs_on_server_log_event(FolderId folder_id, const vector<DialogId> &dialog_ids);
uint64 save_toggle_dialog_is_marked_as_unread_on_server_log_event(DialogId dialog_id, bool is_marked_as_unread); static uint64 save_toggle_dialog_is_marked_as_unread_on_server_log_event(DialogId dialog_id,
bool is_marked_as_unread);
uint64 save_toggle_dialog_is_blocked_on_server_log_event(DialogId dialog_id, bool is_blocked); static uint64 save_toggle_dialog_is_blocked_on_server_log_event(DialogId dialog_id, bool is_blocked);
uint64 save_read_message_contents_on_server_log_event(DialogId dialog_id, const vector<MessageId> &message_ids); static uint64 save_read_message_contents_on_server_log_event(DialogId dialog_id,
const vector<MessageId> &message_ids);
uint64 save_update_scope_notification_settings_on_server_log_event(NotificationSettingsScope scope); static uint64 save_update_scope_notification_settings_on_server_log_event(NotificationSettingsScope scope);
uint64 save_reset_all_notification_settings_on_server_log_event(); static uint64 save_reset_all_notification_settings_on_server_log_event();
uint64 save_get_dialog_from_server_log_event(DialogId dialog_id); static uint64 save_get_dialog_from_server_log_event(DialogId dialog_id);
uint64 save_forward_messages_log_event(DialogId to_dialog_id, DialogId from_dialog_id, static uint64 save_forward_messages_log_event(DialogId to_dialog_id, DialogId from_dialog_id,
const vector<Message *> &messages, const vector<MessageId> &message_ids); const vector<Message *> &messages,
const vector<MessageId> &message_ids);
uint64 save_unpin_all_dialog_messages_on_server_log_event(DialogId dialog_id); static uint64 save_unpin_all_dialog_messages_on_server_log_event(DialogId dialog_id);
void suffix_load_loop(Dialog *d); void suffix_load_loop(Dialog *d);
void suffix_load_update_first_message_id(Dialog *d); static void suffix_load_update_first_message_id(Dialog *d);
void suffix_load_query_ready(DialogId dialog_id); void suffix_load_query_ready(DialogId dialog_id);
void suffix_load_add_query(Dialog *d, std::pair<Promise<>, std::function<bool(const Message *)>> query); void suffix_load_add_query(Dialog *d, std::pair<Promise<>, std::function<bool(const Message *)>> query);
void suffix_load_till_date(Dialog *d, int32 date, Promise<> promise); void suffix_load_till_date(Dialog *d, int32 date, Promise<> promise);
@ -3161,7 +3170,6 @@ class MessagesManager final : public Actor {
bool ttl_db_has_query_; bool ttl_db_has_query_;
Slot ttl_db_slot_; Slot ttl_db_slot_;
std::unordered_set<int64> message_random_ids_;
std::unordered_map<int64, FullMessageId> being_sent_messages_; // message_random_id -> message std::unordered_map<int64, FullMessageId> being_sent_messages_; // message_random_id -> message
std::unordered_map<FullMessageId, MessageId, FullMessageIdHash> std::unordered_map<FullMessageId, MessageId, FullMessageIdHash>
@ -3312,7 +3320,10 @@ class MessagesManager final : public Actor {
double start_time; double start_time;
ActiveDialogAction(MessageId top_thread_message_id, UserId user_id, DialogAction action, double start_time) ActiveDialogAction(MessageId top_thread_message_id, UserId user_id, DialogAction action, double start_time)
: top_thread_message_id(top_thread_message_id), user_id(user_id), action(action), start_time(start_time) { : top_thread_message_id(top_thread_message_id)
, user_id(user_id)
, action(std::move(action))
, start_time(start_time) {
} }
}; };

View File

@ -241,7 +241,7 @@ void NotificationManager::init() {
last_loaded_notification_group_key_.last_notification_date = std::numeric_limits<int32>::max(); last_loaded_notification_group_key_.last_notification_date = std::numeric_limits<int32>::max();
if (max_notification_group_count_ != 0) { if (max_notification_group_count_ != 0) {
int32 loaded_groups = 0; int32 loaded_groups = 0;
int32 needed_groups = static_cast<int32>(max_notification_group_count_); auto needed_groups = static_cast<int32>(max_notification_group_count_);
do { do {
loaded_groups += load_message_notification_groups_from_database(needed_groups, false); loaded_groups += load_message_notification_groups_from_database(needed_groups, false);
} while (loaded_groups < needed_groups && last_loaded_notification_group_key_.last_notification_date != 0); } while (loaded_groups < needed_groups && last_loaded_notification_group_key_.last_notification_date != 0);
@ -1769,7 +1769,7 @@ void NotificationManager::on_notifications_removed(
void NotificationManager::remove_added_notifications_from_pending_updates( void NotificationManager::remove_added_notifications_from_pending_updates(
NotificationGroupId group_id, NotificationGroupId group_id,
std::function<bool(const td_api::object_ptr<td_api::notification> &notification)> is_removed) { const std::function<bool(const td_api::object_ptr<td_api::notification> &notification)> &is_removed) {
auto it = pending_updates_.find(group_id.get()); auto it = pending_updates_.find(group_id.get());
if (it == pending_updates_.end()) { if (it == pending_updates_.end()) {
return; return;

View File

@ -111,7 +111,7 @@ class NotificationManager final : public Actor {
void process_push_notification(string payload, Promise<Unit> &&user_promise); void process_push_notification(string payload, Promise<Unit> &&user_promise);
static Result<int64> get_push_receiver_id(string push); static Result<int64> get_push_receiver_id(string payload);
static Result<string> decrypt_push(int64 encryption_key_id, string encryption_key, string push); // public for tests static Result<string> decrypt_push(int64 encryption_key_id, string encryption_key, string push); // public for tests
@ -290,7 +290,7 @@ class NotificationManager final : public Actor {
void remove_added_notifications_from_pending_updates( void remove_added_notifications_from_pending_updates(
NotificationGroupId group_id, NotificationGroupId group_id,
std::function<bool(const td_api::object_ptr<td_api::notification> &notification)> is_removed); const std::function<bool(const td_api::object_ptr<td_api::notification> &notification)> &is_removed);
void flush_pending_updates(int32 group_id, const char *source); void flush_pending_updates(int32 group_id, const char *source);

View File

@ -656,7 +656,7 @@ Result<PasswordManager::PasswordInputSettings> PasswordManager::get_password_inp
new_password_hash = new_hash.move_as_ok(); new_password_hash = new_hash.move_as_ok();
new_algo = make_tl_object<telegram_api::passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow>( new_algo = make_tl_object<telegram_api::passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow>(
std::move(new_client_salt), BufferSlice(state.server_salt), state.srp_g, BufferSlice(state.srp_p)); std::move(new_client_salt), BufferSlice(state.server_salt), state.srp_g, BufferSlice(state.srp_p));
new_hint = std::move(update_settings.new_hint); new_hint = update_settings.new_hint;
if (have_secret) { if (have_secret) {
update_secure_secret = true; update_secure_secret = true;
} }

View File

@ -1228,7 +1228,7 @@ void send_payment_form(Td *td, FullMessageId full_message_id, int64 payment_form
if (!clean_input_string(credentials_id)) { if (!clean_input_string(credentials_id)) {
return promise.set_error(Status::Error(400, "Credentials identifier must be encoded in UTF-8")); return promise.set_error(Status::Error(400, "Credentials identifier must be encoded in UTF-8"));
} }
auto temp_password_state = td->password_manager_->get_actor_unsafe()->get_temp_password_state_sync(); auto temp_password_state = PasswordManager::get_temp_password_state_sync();
if (!temp_password_state.has_temp_password) { if (!temp_password_state.has_temp_password) {
return promise.set_error(Status::Error(400, "Temporary password required to use saved credentials")); return promise.set_error(Status::Error(400, "Temporary password required to use saved credentials"));
} }

View File

@ -47,7 +47,7 @@ class PhoneNumberManager final : public NetActor {
void on_new_query(uint64 query_id); void on_new_query(uint64 query_id);
void on_query_error(Status status); void on_query_error(Status status);
void on_query_error(uint64 id, Status status); static void on_query_error(uint64 id, Status status);
void on_query_ok(); void on_query_ok();
void start_net_query(NetQueryType net_query_type, NetQueryPtr net_query); void start_net_query(NetQueryType net_query_type, NetQueryPtr net_query);

View File

@ -448,8 +448,8 @@ Variant<PhotoSize, string> get_photo_size(FileManager *file_manager, PhotoSizeSo
source.thumbnail().thumbnail_type = res.type; source.thumbnail().thumbnail_type = res.type;
} }
res.file_id = res.file_id = register_photo(file_manager, source, id, access_hash, std::move(file_reference), owner_dialog_id,
register_photo(file_manager, source, id, access_hash, file_reference, owner_dialog_id, res.size, dc_id, format); res.size, dc_id, format);
if (!content.empty()) { if (!content.empty()) {
file_manager->set_content(res.file_id, std::move(content)); file_manager->set_content(res.file_id, std::move(content));
@ -481,8 +481,8 @@ AnimationSize get_animation_size(FileManager *file_manager, PhotoSizeSource sour
source.thumbnail().thumbnail_type = res.type; source.thumbnail().thumbnail_type = res.type;
} }
res.file_id = register_photo(file_manager, source, id, access_hash, file_reference, owner_dialog_id, res.size, dc_id, res.file_id = register_photo(file_manager, source, id, access_hash, std::move(file_reference), owner_dialog_id,
PhotoFormat::Mpeg4); res.size, dc_id, PhotoFormat::Mpeg4);
return res; return res;
} }

View File

@ -150,7 +150,7 @@ string PhotoSizeSource::get_unique_name(int64 photo_id) const {
UNREACHABLE(); UNREACHABLE();
break; break;
} }
return 0; return string();
} }
static bool operator==(const PhotoSizeSource::Legacy &lhs, const PhotoSizeSource::Legacy &rhs) { static bool operator==(const PhotoSizeSource::Legacy &lhs, const PhotoSizeSource::Legacy &rhs) {

View File

@ -617,7 +617,6 @@ PollId PollManager::create_poll(string &&question, vector<string> &&options, boo
CHECK(is_local_poll_id(poll_id)); CHECK(is_local_poll_id(poll_id));
bool is_inserted = polls_.emplace(poll_id, std::move(poll)).second; bool is_inserted = polls_.emplace(poll_id, std::move(poll)).second;
CHECK(is_inserted); CHECK(is_inserted);
LOG(INFO) << "Created " << poll_id << " with question \"" << oneline(question) << '"';
return poll_id; return poll_id;
} }
@ -979,7 +978,7 @@ void PollManager::get_poll_voters(PollId poll_id, FullMessageId full_message_id,
auto query_promise = auto query_promise =
PromiseCreator::lambda([actor_id = actor_id(this), poll_id, option_id, offset = voters.next_offset, PromiseCreator::lambda([actor_id = actor_id(this), poll_id, option_id, offset = voters.next_offset,
limit](Result<tl_object_ptr<telegram_api::messages_votesList>> &&result) { limit](Result<tl_object_ptr<telegram_api::messages_votesList>> &&result) mutable {
send_closure(actor_id, &PollManager::on_get_poll_voters, poll_id, option_id, std::move(offset), limit, send_closure(actor_id, &PollManager::on_get_poll_voters, poll_id, option_id, std::move(offset), limit,
std::move(result)); std::move(result));
}); });

View File

@ -167,7 +167,7 @@ class PollManager final : public Actor {
static string get_poll_database_key(PollId poll_id); static string get_poll_database_key(PollId poll_id);
void save_poll(const Poll *poll, PollId poll_id); static void save_poll(const Poll *poll, PollId poll_id);
void on_load_poll_from_database(PollId poll_id, string value); void on_load_poll_from_database(PollId poll_id, string value);

View File

@ -259,7 +259,7 @@ std::pair<int32, vector<DialogId>> RecentDialogList::get_dialogs(int32 limit, Pr
update_dialogs(); update_dialogs();
CHECK(limit >= 0); CHECK(limit >= 0);
int32 total_count = narrow_cast<int32>(dialog_ids_.size()); auto total_count = narrow_cast<int32>(dialog_ids_.size());
return {total_count, vector<DialogId>(dialog_ids_.begin(), dialog_ids_.begin() + min(limit, total_count))}; return {total_count, vector<DialogId>(dialog_ids_.begin(), dialog_ids_.begin() + min(limit, total_count))};
} }

View File

@ -132,8 +132,10 @@ void SecretChatActor::on_result_resendable(NetQueryPtr net_query, Promise<NetQue
return on_read_history(std::move(net_query)); return on_read_history(std::move(net_query));
case static_cast<uint8>(QueryType::Ignore): case static_cast<uint8>(QueryType::Ignore):
return Status::OK(); return Status::OK();
default:
UNREACHABLE();
return Status::OK();
} }
UNREACHABLE();
}()); }());
loop(); loop();
@ -963,8 +965,8 @@ Status SecretChatActor::do_inbound_message_decrypted_unchecked(unique_ptr<log_ev
auto *action_resend = auto *action_resend =
static_cast<secret_api::decryptedMessageActionResend *>(decrypted_message_service->action_.get()); static_cast<secret_api::decryptedMessageActionResend *>(decrypted_message_service->action_.get());
uint32 start_seq_no = static_cast<uint32>(action_resend->start_seq_no_ / 2); auto start_seq_no = static_cast<uint32>(action_resend->start_seq_no_ / 2);
uint32 finish_seq_no = static_cast<uint32>(action_resend->end_seq_no_ / 2); auto finish_seq_no = static_cast<uint32>(action_resend->end_seq_no_ / 2);
if (start_seq_no + MAX_RESEND_COUNT < finish_seq_no) { if (start_seq_no + MAX_RESEND_COUNT < finish_seq_no) {
message->promise.set_value(Unit()); message->promise.set_value(Unit());
return Status::Error(PSLICE() << "Won't resend more than " << MAX_RESEND_COUNT << " messages"); return Status::Error(PSLICE() << "Won't resend more than " << MAX_RESEND_COUNT << " messages");
@ -1976,29 +1978,36 @@ void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionSetMe
context_->secret_chat_db()->set_value(config_state_); context_->secret_chat_db()->set_value(config_state_);
send_update_secret_chat(); send_update_secret_chat();
} }
void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionReadMessages &read_messages) { void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionReadMessages &read_messages) {
// TODO // TODO
} }
void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionDeleteMessages &delete_messages) { void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionDeleteMessages &delete_messages) {
// Corresponding log event won't be deleted before promise returned by add_changes is set. // Corresponding log event won't be deleted before promise returned by add_changes is set.
on_delete_messages(delete_messages.random_ids_).ensure(); on_delete_messages(delete_messages.random_ids_).ensure();
} }
void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionScreenshotMessages &screenshot) { void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionScreenshotMessages &screenshot) {
// noting to do // nothing to do
} }
void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionFlushHistory &flush_history) { void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionFlushHistory &flush_history) {
on_flush_history(pfs_state_.message_id).ensure(); on_flush_history(pfs_state_.message_id).ensure();
} }
void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionResend &resend) { void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionResend &resend) {
if (seq_no_state_.resend_end_seq_no < resend.end_seq_no_ / 2) { // replay protection if (seq_no_state_.resend_end_seq_no < resend.end_seq_no_ / 2) { // replay protection
seq_no_state_.resend_end_seq_no = resend.end_seq_no_ / 2; seq_no_state_.resend_end_seq_no = resend.end_seq_no_ / 2;
on_seq_no_state_changed(); on_seq_no_state_changed();
} }
} }
void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionNotifyLayer &notify_layer) { void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionNotifyLayer &notify_layer) {
config_state_.my_layer = notify_layer.layer_; config_state_.my_layer = notify_layer.layer_;
context_->secret_chat_db()->set_value(config_state_); context_->secret_chat_db()->set_value(config_state_);
} }
void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionTyping &typing) { void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionTyping &typing) {
// noop // noop
} }
@ -2009,23 +2018,29 @@ Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionSetM
send_update_secret_chat(); send_update_secret_chat();
return Status::OK(); return Status::OK();
} }
Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionReadMessages &read_messages) { Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionReadMessages &read_messages) {
// TODO // TODO
return Status::OK(); return Status::OK();
} }
Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionDeleteMessages &delete_messages) { Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionDeleteMessages &delete_messages) {
return on_delete_messages(delete_messages.random_ids_); return on_delete_messages(delete_messages.random_ids_);
} }
Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionScreenshotMessages &screenshot) { Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionScreenshotMessages &screenshot) {
// TODO // TODO
return Status::OK(); return Status::OK();
} }
Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionFlushHistory &screenshot) { Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionFlushHistory &screenshot) {
return on_flush_history(pfs_state_.message_id); return on_flush_history(pfs_state_.message_id);
} }
Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionResend &resend) { Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionResend &resend) {
return Status::OK(); return Status::OK();
} }
Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionNotifyLayer &notify_layer) { Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionNotifyLayer &notify_layer) {
if (notify_layer.layer_ > config_state_.his_layer) { if (notify_layer.layer_ > config_state_.his_layer) {
config_state_.his_layer = notify_layer.layer_; config_state_.his_layer = notify_layer.layer_;
@ -2034,6 +2049,7 @@ Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionNoti
} }
return Status::OK(); return Status::OK();
} }
Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionTyping &typing) { Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionTyping &typing) {
// noop // noop
return Status::OK(); return Status::OK();
@ -2045,16 +2061,19 @@ void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionReque
pfs_state_.state = PfsState::WaitRequestResponse; pfs_state_.state = PfsState::WaitRequestResponse;
on_pfs_state_changed(); on_pfs_state_changed();
} }
void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionAcceptKey &accept_key) { void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionAcceptKey &accept_key) {
CHECK(pfs_state_.state == PfsState::WaitSendAccept || pfs_state_.state == PfsState::SendAccept); CHECK(pfs_state_.state == PfsState::WaitSendAccept || pfs_state_.state == PfsState::SendAccept);
pfs_state_.state = PfsState::WaitAcceptResponse; pfs_state_.state = PfsState::WaitAcceptResponse;
pfs_state_.handshake = mtproto::DhHandshake(); pfs_state_.handshake = mtproto::DhHandshake();
on_pfs_state_changed(); on_pfs_state_changed();
} }
void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionAbortKey &abort_key) { void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionAbortKey &abort_key) {
// TODO // TODO
LOG(FATAL) << "TODO"; LOG(FATAL) << "TODO";
} }
void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionCommitKey &commit_key) { void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionCommitKey &commit_key) {
CHECK(pfs_state_.state == PfsState::WaitSendCommit || pfs_state_.state == PfsState::SendCommit); CHECK(pfs_state_.state == PfsState::WaitSendCommit || pfs_state_.state == PfsState::SendCommit);
@ -2069,11 +2088,11 @@ void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionCommi
on_pfs_state_changed(); on_pfs_state_changed();
} }
void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionNoop &noop) { void SecretChatActor::on_outbound_action(secret_api::decryptedMessageActionNoop &noop) {
// noop // noop
} }
// decryptedMessageActionRequestKey#f3c9611b exchange_id:long g_a:bytes = DecryptedMessageAction;
Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionRequestKey &request_key) { Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionRequestKey &request_key) {
if (pfs_state_.state == PfsState::WaitRequestResponse || pfs_state_.state == PfsState::SendRequest) { if (pfs_state_.state == PfsState::WaitRequestResponse || pfs_state_.state == PfsState::SendRequest) {
if (pfs_state_.exchange_id > request_key.exchange_id_) { if (pfs_state_.exchange_id > request_key.exchange_id_) {
@ -2112,7 +2131,6 @@ Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionRequ
return Status::OK(); return Status::OK();
} }
// decryptedMessageActionAcceptKey#6fe1735b exchange_id:long g_b:bytes key_fingerprint:long = DecryptedMessageAction;
Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionAcceptKey &accept_key) { Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionAcceptKey &accept_key) {
if (pfs_state_.state != PfsState::WaitRequestResponse) { if (pfs_state_.state != PfsState::WaitRequestResponse) {
return Status::Error("AcceptKey: unexpected"); return Status::Error("AcceptKey: unexpected");
@ -2136,6 +2154,7 @@ Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionAcce
on_pfs_state_changed(); on_pfs_state_changed();
return Status::OK(); return Status::OK();
} }
Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionAbortKey &abort_key) { Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionAbortKey &abort_key) {
if (pfs_state_.exchange_id != abort_key.exchange_id_) { if (pfs_state_.exchange_id != abort_key.exchange_id_) {
LOG(INFO) << "AbortKey: exchange_id mismatch: " << tag("my exchange_id", pfs_state_.exchange_id) LOG(INFO) << "AbortKey: exchange_id mismatch: " << tag("my exchange_id", pfs_state_.exchange_id)
@ -2151,6 +2170,7 @@ Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionAbor
on_pfs_state_changed(); on_pfs_state_changed();
return Status::OK(); return Status::OK();
} }
Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionCommitKey &commit_key) { Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionCommitKey &commit_key) {
if (pfs_state_.state != PfsState::WaitAcceptResponse) { if (pfs_state_.state != PfsState::WaitAcceptResponse) {
return Status::Error("CommitKey: unexpected"); return Status::Error("CommitKey: unexpected");
@ -2174,6 +2194,7 @@ Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionComm
on_pfs_state_changed(); on_pfs_state_changed();
return Status::OK(); return Status::OK();
} }
Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionNoop &noop) { Status SecretChatActor::on_inbound_action(secret_api::decryptedMessageActionNoop &noop) {
// noop // noop
return Status::OK(); return Status::OK();
@ -2224,7 +2245,6 @@ void SecretChatActor::on_outbound_action(secret_api::DecryptedMessageAction &act
downcast_call(action, [&](auto &obj) { this->on_outbound_action(obj); }); downcast_call(action, [&](auto &obj) { this->on_outbound_action(obj); });
} }
// decryptedMessageActionRequestKey#f3c9611b exchange_id:long g_a:bytes = DecryptedMessageAction;
void SecretChatActor::request_new_key() { void SecretChatActor::request_new_key() {
CHECK(!auth_state_.dh_config.empty()); CHECK(!auth_state_.dh_config.empty());

View File

@ -645,7 +645,7 @@ class SecretChatActor final : public NetQueryCallback {
Status save_common_info(T &update); Status save_common_info(T &update);
int32 current_layer() const { int32 current_layer() const {
int32 layer = static_cast<int32>(SecretChatLayer::Current); auto layer = static_cast<int32>(SecretChatLayer::Current);
if (config_state_.his_layer < layer) { if (config_state_.his_layer < layer) {
layer = config_state_.his_layer; layer = config_state_.his_layer;
} }

View File

@ -169,7 +169,7 @@ void SecretChatsManager::on_update_chat(tl_object_ptr<telegram_api::updateEncryp
return; return;
} }
bool chat_requested = update->chat_->get_id() == telegram_api::encryptedChatRequested::ID; bool chat_requested = update->chat_->get_id() == telegram_api::encryptedChatRequested::ID;
pending_chat_updates_.push_back({Timestamp::in(chat_requested ? 1 : 0), std::move(update)}); pending_chat_updates_.emplace_back(Timestamp::in(chat_requested ? 1 : 0), std::move(update));
flush_pending_chat_updates(); flush_pending_chat_updates();
} }

View File

@ -104,11 +104,11 @@ class SetSecureValue final : public NetQueryCallback {
void on_upload_ok(FileId file_id, tl_object_ptr<telegram_api::InputFile> input_file) final; void on_upload_ok(FileId file_id, tl_object_ptr<telegram_api::InputFile> input_file) final;
void on_upload_encrypted_ok(FileId file_id, tl_object_ptr<telegram_api::InputEncryptedFile> input_file) final; void on_upload_encrypted_ok(FileId file_id, tl_object_ptr<telegram_api::InputEncryptedFile> input_file) final;
void on_upload_secure_ok(FileId file_id, tl_object_ptr<telegram_api::InputSecureFile> input_file) final; void on_upload_secure_ok(FileId file_id, tl_object_ptr<telegram_api::InputSecureFile> input_file) final;
void on_upload_error(FileId file_id, Status status) final; void on_upload_error(FileId file_id, Status error) final;
}; };
void on_upload_ok(FileId file_id, tl_object_ptr<telegram_api::InputSecureFile> input_file, uint32 upload_generation); void on_upload_ok(FileId file_id, tl_object_ptr<telegram_api::InputSecureFile> input_file, uint32 upload_generation);
void on_upload_error(FileId file_id, Status status, uint32 upload_generation); void on_upload_error(FileId file_id, Status error, uint32 upload_generation);
void on_error(Status error); void on_error(Status error);
@ -125,7 +125,7 @@ class SetSecureValue final : public NetQueryCallback {
void cancel_upload(); void cancel_upload();
void start_upload_all(); void start_upload_all();
void start_upload(FileManager *file_manager, FileId &file_id, SecureInputFile &info); void start_upload(FileManager *file_manager, FileId &file_id, SecureInputFile &info);
void merge(FileManager *file_manager, FileId file_id, EncryptedSecureFile &encrypted_file); static void merge(FileManager *file_manager, FileId file_id, EncryptedSecureFile &encrypted_file);
}; };
class SetSecureValueErrorsQuery final : public Td::ResultHandler { class SetSecureValueErrorsQuery final : public Td::ResultHandler {
@ -285,7 +285,7 @@ void GetAllSecureValues::loop() {
auto secure_values = transform(r_secure_values.move_as_ok(), auto secure_values = transform(r_secure_values.move_as_ok(),
[](SecureValueWithCredentials &&value) { return std::move(value.value); }); [](SecureValueWithCredentials &&value) { return std::move(value.value); });
promise_.set_value(get_passport_elements_object(file_manager, std::move(secure_values))); promise_.set_value(get_passport_elements_object(file_manager, secure_values));
stop(); stop();
} }
@ -959,7 +959,7 @@ void SecureManager::get_passport_authorization_form(UserId bot_user_id, string s
form.bot_user_id = bot_user_id; form.bot_user_id = bot_user_id;
form.scope = scope; form.scope = scope;
form.public_key = public_key; form.public_key = public_key;
form.nonce = nonce; form.nonce = std::move(nonce);
auto new_promise = PromiseCreator::lambda( auto new_promise = PromiseCreator::lambda(
[actor_id = actor_id(this), authorization_form_id, promise = std::move(promise)]( [actor_id = actor_id(this), authorization_form_id, promise = std::move(promise)](
Result<telegram_api::object_ptr<telegram_api::account_authorizationForm>> r_authorization_form) mutable { Result<telegram_api::object_ptr<telegram_api::account_authorizationForm>> r_authorization_form) mutable {
@ -1100,7 +1100,7 @@ void SecureManager::on_get_passport_authorization_form_secret(int32 authorizatio
on_get_secure_value(r_secure_value.ok()); on_get_secure_value(r_secure_value.ok());
auto secure_value = r_secure_value.move_as_ok(); auto secure_value = r_secure_value.move_as_ok();
auto r_passport_element = get_passport_element_object(file_manager, std::move(secure_value.value)); auto r_passport_element = get_passport_element_object(file_manager, secure_value.value);
if (r_passport_element.is_error()) { if (r_passport_element.is_error()) {
LOG(ERROR) << "Failed to get passport element object: " << r_passport_element.error(); LOG(ERROR) << "Failed to get passport element object: " << r_passport_element.error();
break; break;

View File

@ -39,9 +39,13 @@ class SecureManager final : public NetQueryCallback {
explicit SecureManager(ActorShared<> parent); explicit SecureManager(ActorShared<> parent);
void get_secure_value(std::string password, SecureValueType type, Promise<TdApiSecureValue> promise); void get_secure_value(std::string password, SecureValueType type, Promise<TdApiSecureValue> promise);
void get_all_secure_values(std::string password, Promise<TdApiSecureValues> promise); void get_all_secure_values(std::string password, Promise<TdApiSecureValues> promise);
void set_secure_value(string password, SecureValue secure_value, Promise<TdApiSecureValue> promise); void set_secure_value(string password, SecureValue secure_value, Promise<TdApiSecureValue> promise);
void delete_secure_value(SecureValueType type, Promise<Unit> promise); void delete_secure_value(SecureValueType type, Promise<Unit> promise);
void set_secure_value_errors(Td *td, tl_object_ptr<telegram_api::InputUser> input_user, void set_secure_value_errors(Td *td, tl_object_ptr<telegram_api::InputUser> input_user,
vector<tl_object_ptr<td_api::inputPassportElementError>> errors, Promise<Unit> promise); vector<tl_object_ptr<td_api::inputPassportElementError>> errors, Promise<Unit> promise);

View File

@ -208,7 +208,7 @@ Secret Secret::create_new() {
auto secret_slice = ::td::as_slice(secret); auto secret_slice = ::td::as_slice(secret);
Random::secure_bytes(secret_slice); Random::secure_bytes(secret_slice);
auto checksum_diff = secret_checksum(secret_slice); auto checksum_diff = secret_checksum(secret_slice);
uint8 new_byte = static_cast<uint8>((static_cast<uint32>(secret_slice.ubegin()[0]) + checksum_diff) % 255); auto new_byte = static_cast<uint8>((static_cast<uint32>(secret_slice.ubegin()[0]) + checksum_diff) % 255);
secret_slice.ubegin()[0] = new_byte; secret_slice.ubegin()[0] = new_byte;
return create(secret_slice).move_as_ok(); return create(secret_slice).move_as_ok();
} }
@ -364,7 +364,7 @@ Result<BufferSlice> decrypt_value(const Secret &secret, const ValueHash &hash, S
return std::move(decrypted_value); return std::move(decrypted_value);
} }
Result<ValueHash> encrypt_file(const Secret &secret, std::string src, std::string dest) { Result<ValueHash> encrypt_file(const Secret &secret, const string &src, const string &dest) {
TRY_RESULT(src_file, FileFd::open(src, FileFd::Flags::Read)); TRY_RESULT(src_file, FileFd::open(src, FileFd::Flags::Read));
TRY_RESULT(dest_file, FileFd::open(dest, FileFd::Flags::Truncate | FileFd::Flags::Write | FileFd::Create)); TRY_RESULT(dest_file, FileFd::open(dest, FileFd::Flags::Truncate | FileFd::Flags::Write | FileFd::Create));
TRY_RESULT(src_file_size, src_file.get_size()); TRY_RESULT(src_file_size, src_file.get_size());
@ -382,7 +382,7 @@ Result<ValueHash> encrypt_file(const Secret &secret, std::string src, std::strin
return std::move(hash); return std::move(hash);
} }
Status decrypt_file(const Secret &secret, const ValueHash &hash, std::string src, std::string dest) { Status decrypt_file(const Secret &secret, const ValueHash &hash, const string &src, const string &dest) {
TRY_RESULT(src_file, FileFd::open(src, FileFd::Flags::Read)); TRY_RESULT(src_file, FileFd::open(src, FileFd::Flags::Read));
TRY_RESULT(dest_file, FileFd::open(dest, FileFd::Flags::Truncate | FileFd::Flags::Write | FileFd::Create)); TRY_RESULT(dest_file, FileFd::open(dest, FileFd::Flags::Truncate | FileFd::Flags::Write | FileFd::Create));
TRY_RESULT(src_file_size, src_file.get_size()); TRY_RESULT(src_file_size, src_file.get_size());

View File

@ -184,10 +184,12 @@ struct EncryptedValue {
}; };
Result<EncryptedValue> encrypt_value(const Secret &secret, Slice data); Result<EncryptedValue> encrypt_value(const Secret &secret, Slice data);
Result<ValueHash> encrypt_file(const Secret &secret, std::string src, std::string dest);
Result<BufferSlice> decrypt_value(const Secret &secret, const ValueHash &hash, Slice data); Result<BufferSlice> decrypt_value(const Secret &secret, const ValueHash &hash, Slice data);
Status decrypt_file(const Secret &secret, const ValueHash &hash, std::string src, std::string dest);
Result<ValueHash> encrypt_file(const Secret &secret, const string &src, const string &dest);
Status decrypt_file(const Secret &secret, const ValueHash &hash, const string &src, const string &dest);
} // namespace secure_storage } // namespace secure_storage
} // namespace td } // namespace td

View File

@ -517,7 +517,6 @@ static bool check_encrypted_secure_value(const EncryptedSecureValue &value) {
case SecureValueType::TemporaryRegistration: case SecureValueType::TemporaryRegistration:
return !has_encrypted_data && !has_plain_data && has_files && !has_front_side && !has_reverse_side && !has_selfie; return !has_encrypted_data && !has_plain_data && has_files && !has_front_side && !has_reverse_side && !has_selfie;
case SecureValueType::PhoneNumber: case SecureValueType::PhoneNumber:
return has_plain_data && !has_files && !has_front_side && !has_reverse_side && !has_selfie && !has_translations;
case SecureValueType::EmailAddress: case SecureValueType::EmailAddress:
return has_plain_data && !has_files && !has_front_side && !has_reverse_side && !has_selfie && !has_translations; return has_plain_data && !has_files && !has_front_side && !has_reverse_side && !has_selfie && !has_translations;
case SecureValueType::None: case SecureValueType::None:
@ -848,8 +847,7 @@ static Status check_document_number(string &number) {
} }
static Result<DatedFile> get_secure_file(FileManager *file_manager, td_api::object_ptr<td_api::InputFile> &&file) { static Result<DatedFile> get_secure_file(FileManager *file_manager, td_api::object_ptr<td_api::InputFile> &&file) {
TRY_RESULT(file_id, TRY_RESULT(file_id, file_manager->get_input_file_id(FileType::Secure, file, DialogId(), false, false, false, true));
file_manager->get_input_file_id(FileType::Secure, std::move(file), DialogId(), false, false, false, true));
DatedFile result; DatedFile result;
result.file_id = file_id; result.file_id = file_id;
result.date = G()->unix_time(); result.date = G()->unix_time();
@ -1294,7 +1292,7 @@ static EncryptedSecureFile encrypt_secure_file(FileManager *file_manager, const
static vector<EncryptedSecureFile> encrypt_secure_files(FileManager *file_manager, static vector<EncryptedSecureFile> encrypt_secure_files(FileManager *file_manager,
const secure_storage::Secret &master_secret, const secure_storage::Secret &master_secret,
vector<DatedFile> files, string &to_hash) { const vector<DatedFile> &files, string &to_hash) {
return transform( return transform(
files, [&](auto dated_file) { return encrypt_secure_file(file_manager, master_secret, dated_file, to_hash); }); files, [&](auto dated_file) { return encrypt_secure_file(file_manager, master_secret, dated_file, to_hash); });
/* /*

View File

@ -53,9 +53,9 @@ telegram_api::object_ptr<telegram_api::codeSettings> SendCodeHelper::get_input_c
false /*ignored*/); false /*ignored*/);
} }
telegram_api::auth_sendCode SendCodeHelper::send_code(Slice phone_number, const Settings &settings, int32 api_id, telegram_api::auth_sendCode SendCodeHelper::send_code(string phone_number, const Settings &settings, int32 api_id,
const string &api_hash) { const string &api_hash) {
phone_number_ = phone_number.str(); phone_number_ = std::move(phone_number);
return telegram_api::auth_sendCode(phone_number_, api_id, api_hash, get_input_code_settings(settings)); return telegram_api::auth_sendCode(phone_number_, api_id, api_hash, get_input_code_settings(settings));
} }
@ -86,11 +86,11 @@ SendCodeHelper::AuthenticationCodeInfo SendCodeHelper::get_authentication_code_i
switch (code_type_ptr->get_id()) { switch (code_type_ptr->get_id()) {
case telegram_api::auth_codeTypeSms::ID: case telegram_api::auth_codeTypeSms::ID:
return {AuthenticationCodeInfo::Type::Sms, 0, ""}; return {AuthenticationCodeInfo::Type::Sms, 0, string()};
case telegram_api::auth_codeTypeCall::ID: case telegram_api::auth_codeTypeCall::ID:
return {AuthenticationCodeInfo::Type::Call, 0, ""}; return {AuthenticationCodeInfo::Type::Call, 0, string()};
case telegram_api::auth_codeTypeFlashCall::ID: case telegram_api::auth_codeTypeFlashCall::ID:
return {AuthenticationCodeInfo::Type::FlashCall, 0, ""}; return {AuthenticationCodeInfo::Type::FlashCall, 0, string()};
default: default:
UNREACHABLE(); UNREACHABLE();
return AuthenticationCodeInfo(); return AuthenticationCodeInfo();

View File

@ -25,7 +25,7 @@ class SendCodeHelper {
using Settings = td_api::object_ptr<td_api::phoneNumberAuthenticationSettings>; using Settings = td_api::object_ptr<td_api::phoneNumberAuthenticationSettings>;
telegram_api::auth_sendCode send_code(Slice phone_number, const Settings &settings, int32 api_id, telegram_api::auth_sendCode send_code(string phone_number, const Settings &settings, int32 api_id,
const string &api_hash); const string &api_hash);
telegram_api::account_sendChangePhoneCode send_change_phone_code(Slice phone_number, const Settings &settings); telegram_api::account_sendChangePhoneCode send_change_phone_code(Slice phone_number, const Settings &settings);

View File

@ -624,7 +624,7 @@ class ReorderStickerSetsQuery final : public Td::ResultHandler {
bool is_masks_; bool is_masks_;
public: public:
void send(bool is_masks, vector<StickerSetId> sticker_set_ids) { void send(bool is_masks, const vector<StickerSetId> &sticker_set_ids) {
is_masks_ = is_masks; is_masks_ = is_masks;
int32 flags = 0; int32 flags = 0;
if (is_masks) { if (is_masks) {
@ -833,7 +833,7 @@ class UninstallStickerSetQuery final : public Td::ResultHandler {
class ReadFeaturedStickerSetsQuery final : public Td::ResultHandler { class ReadFeaturedStickerSetsQuery final : public Td::ResultHandler {
public: public:
void send(vector<StickerSetId> sticker_set_ids) { void send(const vector<StickerSetId> &sticker_set_ids) {
LOG(INFO) << "Read trending sticker sets " << format::as_array(sticker_set_ids); LOG(INFO) << "Read trending sticker sets " << format::as_array(sticker_set_ids);
send_query(G()->net_query_creator().create( send_query(G()->net_query_creator().create(
telegram_api::messages_readFeaturedStickers(StickersManager::convert_sticker_set_ids(sticker_set_ids)))); telegram_api::messages_readFeaturedStickers(StickersManager::convert_sticker_set_ids(sticker_set_ids))));
@ -1636,6 +1636,7 @@ vector<td_api::object_ptr<td_api::closedVectorPath>> StickersManager::get_sticke
} }
if (!commands.empty()) { if (!commands.empty()) {
result.push_back(td_api::make_object<td_api::closedVectorPath>(std::move(commands))); result.push_back(td_api::make_object<td_api::closedVectorPath>(std::move(commands)));
commands.clear();
} }
is_closed = true; is_closed = true;
break; break;
@ -2339,11 +2340,11 @@ void StickersManager::add_sticker_thumbnail(Sticker *s, PhotoSize thumbnail) {
return; return;
} }
if (thumbnail.type == 'm') { if (thumbnail.type == 'm') {
s->m_thumbnail = thumbnail; s->m_thumbnail = std::move(thumbnail);
return; return;
} }
if (thumbnail.type == 's' || thumbnail.type == 't') { if (thumbnail.type == 's' || thumbnail.type == 't') {
s->s_thumbnail = thumbnail; s->s_thumbnail = std::move(thumbnail);
return; return;
} }
LOG(ERROR) << "Receive sticker thumbnail of unsupported type " << thumbnail.type; LOG(ERROR) << "Receive sticker thumbnail of unsupported type " << thumbnail.type;
@ -2363,7 +2364,7 @@ void StickersManager::create_sticker(FileId file_id, string minithumbnail, Photo
if (!td_->auth_manager_->is_bot()) { if (!td_->auth_manager_->is_bot()) {
s->minithumbnail = std::move(minithumbnail); s->minithumbnail = std::move(minithumbnail);
} }
add_sticker_thumbnail(s.get(), thumbnail); add_sticker_thumbnail(s.get(), std::move(thumbnail));
if (sticker != nullptr) { if (sticker != nullptr) {
s->set_id = on_get_input_sticker_set(file_id, std::move(sticker->stickerset_), load_data_multipromise_ptr); s->set_id = on_get_input_sticker_set(file_id, std::move(sticker->stickerset_), load_data_multipromise_ptr);
s->alt = std::move(sticker->alt_); s->alt = std::move(sticker->alt_);
@ -4342,15 +4343,15 @@ void StickersManager::schedule_update_animated_emoji_clicked(const StickerSet *s
auto now = Time::now(); auto now = Time::now();
auto start_time = max(now, next_update_animated_emoji_clicked_time_); auto start_time = max(now, next_update_animated_emoji_clicked_time_);
for (size_t i = 0; i < clicks.size(); i++) { for (const auto &click : clicks) {
auto index = clicks[i].first; auto index = click.first;
auto sticker_id = sticker_ids[index]; auto sticker_id = sticker_ids[index];
if (!sticker_id.is_valid()) { if (!sticker_id.is_valid()) {
LOG(INFO) << "Failed to find sticker for " << emoji << " with index " << index; LOG(INFO) << "Failed to find sticker for " << emoji << " with index " << index;
return; return;
} }
create_actor<SleepActor>( create_actor<SleepActor>(
"SendUpdateAnimatedEmojiClicked", start_time + clicks[i].second - now, "SendUpdateAnimatedEmojiClicked", start_time + click.second - now,
PromiseCreator::lambda([actor_id = actor_id(this), full_message_id, sticker_id](Result<Unit> result) { PromiseCreator::lambda([actor_id = actor_id(this), full_message_id, sticker_id](Result<Unit> result) {
send_closure(actor_id, &StickersManager::send_update_animated_emoji_clicked, full_message_id, sticker_id); send_closure(actor_id, &StickersManager::send_update_animated_emoji_clicked, full_message_id, sticker_id);
})) }))
@ -5481,7 +5482,7 @@ void StickersManager::on_new_stickers_uploaded(int64 random_id, Result<Unit> res
td_->create_handler<CreateNewStickerSetQuery>(std::move(pending_new_sticker_set->promise)) td_->create_handler<CreateNewStickerSetQuery>(std::move(pending_new_sticker_set->promise))
->send(std::move(input_user), pending_new_sticker_set->title, pending_new_sticker_set->short_name, is_masks, ->send(std::move(input_user), pending_new_sticker_set->title, pending_new_sticker_set->short_name, is_masks,
is_animated, std::move(input_stickers), std::move(pending_new_sticker_set->software)); is_animated, std::move(input_stickers), pending_new_sticker_set->software);
} }
void StickersManager::add_sticker_to_set(UserId user_id, string &short_name, void StickersManager::add_sticker_to_set(UserId user_id, string &short_name,
@ -6630,7 +6631,7 @@ double StickersManager::get_emoji_language_code_last_difference_time(const strin
return it->second; return it->second;
} }
auto &result = emoji_language_code_last_difference_times_[language_code]; auto &result = emoji_language_code_last_difference_times_[language_code];
int32 old_unix_time = to_integer<int32>(G()->td_db()->get_sqlite_sync_pmc()->get( auto old_unix_time = to_integer<int32>(G()->td_db()->get_sqlite_sync_pmc()->get(
get_emoji_language_code_last_difference_time_database_key(language_code))); get_emoji_language_code_last_difference_time_database_key(language_code)));
int32 passed_time = max(static_cast<int32>(0), G()->unix_time() - old_unix_time); int32 passed_time = max(static_cast<int32>(0), G()->unix_time() - old_unix_time);
result = Time::now_cached() - passed_time; result = Time::now_cached() - passed_time;

View File

@ -175,7 +175,7 @@ class StickersManager final : public Actor {
FileId upload_sticker_file(UserId user_id, tl_object_ptr<td_api::InputSticker> &&sticker, Promise<Unit> &&promise); FileId upload_sticker_file(UserId user_id, tl_object_ptr<td_api::InputSticker> &&sticker, Promise<Unit> &&promise);
void get_suggested_sticker_set_name(string short_name, Promise<string> &&promise); void get_suggested_sticker_set_name(string title, Promise<string> &&promise);
enum class CheckStickerSetNameResult : uint8 { Ok, Invalid, Occupied }; enum class CheckStickerSetNameResult : uint8 { Ok, Invalid, Occupied };
void check_sticker_set_name(const string &name, Promise<CheckStickerSetNameResult> &&promise); void check_sticker_set_name(const string &name, Promise<CheckStickerSetNameResult> &&promise);
@ -284,7 +284,7 @@ class StickersManager final : public Actor {
void on_uploaded_sticker_file(FileId file_id, tl_object_ptr<telegram_api::MessageMedia> media, void on_uploaded_sticker_file(FileId file_id, tl_object_ptr<telegram_api::MessageMedia> media,
Promise<Unit> &&promise); Promise<Unit> &&promise);
void on_find_stickers_success(const string &emoji, tl_object_ptr<telegram_api::messages_Stickers> &&sticker_sets); void on_find_stickers_success(const string &emoji, tl_object_ptr<telegram_api::messages_Stickers> &&stickers);
void on_find_stickers_fail(const string &emoji, Status &&error); void on_find_stickers_fail(const string &emoji, Status &&error);

View File

@ -165,7 +165,7 @@ void StickersManager::store_sticker_set(const StickerSet *sticker_set, bool with
store(sticker_set->minithumbnail, storer); store(sticker_set->minithumbnail, storer);
} }
uint32 stored_sticker_count = narrow_cast<uint32>(is_full ? sticker_set->sticker_ids.size() : stickers_limit); auto stored_sticker_count = narrow_cast<uint32>(is_full ? sticker_set->sticker_ids.size() : stickers_limit);
store(stored_sticker_count, storer); store(stored_sticker_count, storer);
for (uint32 i = 0; i < stored_sticker_count; i++) { for (uint32 i = 0; i < stored_sticker_count; i++) {
auto sticker_id = sticker_set->sticker_ids[i]; auto sticker_id = sticker_set->sticker_ids[i];

View File

@ -65,7 +65,7 @@ void StorageManager::get_storage_stats(bool need_all_files, int32 dialog_limit,
if (is_closed_) { if (is_closed_) {
return promise.set_error(Global::request_aborted_error()); return promise.set_error(Global::request_aborted_error());
} }
if (pending_storage_stats_.size() != 0) { if (!pending_storage_stats_.empty()) {
if (stats_dialog_limit_ == dialog_limit && need_all_files == stats_need_all_files_) { if (stats_dialog_limit_ == dialog_limit && need_all_files == stats_need_all_files_) {
pending_storage_stats_.emplace_back(std::move(promise)); pending_storage_stats_.emplace_back(std::move(promise));
return; return;
@ -118,12 +118,12 @@ void StorageManager::run_gc(FileGcParameters parameters, bool return_deleted_fil
bool split_by_owner_dialog_id = !parameters.owner_dialog_ids.empty() || bool split_by_owner_dialog_id = !parameters.owner_dialog_ids.empty() ||
!parameters.exclude_owner_dialog_ids.empty() || parameters.dialog_limit != 0; !parameters.exclude_owner_dialog_ids.empty() || parameters.dialog_limit != 0;
get_storage_stats(true /*need_all_files*/, split_by_owner_dialog_id, get_storage_stats(
PromiseCreator::lambda( true /*need_all_files*/, split_by_owner_dialog_id,
[actor_id = actor_id(this), parameters = std::move(parameters)](Result<FileStats> file_stats) { PromiseCreator::lambda(
send_closure(actor_id, &StorageManager::on_all_files, std::move(parameters), [actor_id = actor_id(this), parameters = std::move(parameters)](Result<FileStats> file_stats) mutable {
std::move(file_stats)); send_closure(actor_id, &StorageManager::on_all_files, std::move(parameters), std::move(file_stats));
})); }));
//NB: get_storage_stats will cancel all garbage collection queries, so promise needs to be added after the call //NB: get_storage_stats will cancel all garbage collection queries, so promise needs to be added after the call
pending_run_gc_[return_deleted_file_statistics].push_back(std::move(promise)); pending_run_gc_[return_deleted_file_statistics].push_back(std::move(promise));

View File

@ -24,7 +24,7 @@ namespace td {
struct DatabaseStats { struct DatabaseStats {
string debug; string debug;
DatabaseStats() = default; DatabaseStats() = default;
explicit DatabaseStats(string debug) : debug(debug) { explicit DatabaseStats(string debug) : debug(std::move(debug)) {
} }
tl_object_ptr<td_api::databaseStatistics> get_database_statistics_object() const; tl_object_ptr<td_api::databaseStatistics> get_database_statistics_object() const;
}; };
@ -64,7 +64,7 @@ class StorageManager final : public Actor {
void on_file_stats(Result<FileStats> r_file_stats, uint32 generation); void on_file_stats(Result<FileStats> r_file_stats, uint32 generation);
void create_stats_worker(); void create_stats_worker();
void update_fast_stats(const FileStats &stats); void update_fast_stats(const FileStats &stats);
void send_stats(FileStats &&stats, int32 dialog_limit, std::vector<Promise<FileStats>> &&promises); static void send_stats(FileStats &&stats, int32 dialog_limit, std::vector<Promise<FileStats>> &&promises);
void save_fast_stat(); void save_fast_stat();
void load_fast_stat(); void load_fast_stat();

View File

@ -142,8 +142,7 @@ void update_suggested_actions(vector<SuggestedAction> &suggested_actions,
} }
CHECK(!added_actions.empty() || !removed_actions.empty()); CHECK(!added_actions.empty() || !removed_actions.empty());
suggested_actions = std::move(new_suggested_actions); suggested_actions = std::move(new_suggested_actions);
send_closure(G()->td(), &Td::send_update, send_closure(G()->td(), &Td::send_update, get_update_suggested_actions_object(added_actions, removed_actions));
get_update_suggested_actions_object(std::move(added_actions), std::move(removed_actions)));
} }
void remove_suggested_action(vector<SuggestedAction> &suggested_actions, SuggestedAction suggested_action) { void remove_suggested_action(vector<SuggestedAction> &suggested_actions, SuggestedAction suggested_action) {

View File

@ -802,8 +802,8 @@ class LoadChatsRequest final : public RequestActor<> {
// 1 for database + 1 for server request + 1 for server request at the end + 1 for return + 1 just in case // 1 for database + 1 for server request + 1 for server request at the end + 1 for return + 1 just in case
set_tries(5); set_tries(5);
if (limit > 100) { if (limit_ > 100) {
limit = 100; limit_ = 100;
} }
} }
}; };
@ -2827,10 +2827,11 @@ void Td::on_get_terms_of_service(Result<std::pair<int32, TermsOfService>> result
if (result.is_error()) { if (result.is_error()) {
expires_in = Random::fast(10, 60); expires_in = Random::fast(10, 60);
} else { } else {
pending_terms_of_service_ = std::move(result.ok().second); auto terms = result.move_as_ok();
pending_terms_of_service_ = std::move(terms.second);
auto update = get_update_terms_of_service_object(); auto update = get_update_terms_of_service_object();
if (update == nullptr) { if (update == nullptr) {
expires_in = min(max(result.ok().first, G()->unix_time() + 3600) - G()->unix_time(), 86400); expires_in = min(max(terms.first, G()->unix_time() + 3600) - G()->unix_time(), 86400);
} else { } else {
send_update(std::move(update)); send_update(std::move(update));
} }
@ -4115,7 +4116,7 @@ void Td::init_file_manager() {
} }
void reload_photo(PhotoSizeSource source, Promise<Unit> promise) final { void reload_photo(PhotoSizeSource source, Promise<Unit> promise) final {
send_closure(G()->file_reference_manager(), &FileReferenceManager::reload_photo, source, std::move(promise)); FileReferenceManager::reload_photo(std::move(source), std::move(promise));
} }
ActorShared<> create_reference() final { ActorShared<> create_reference() final {
@ -4557,7 +4558,7 @@ void Td::on_request(uint64 id, td_api::checkAuthenticationBotToken &request) {
void Td::on_request(uint64 id, td_api::confirmQrCodeAuthentication &request) { void Td::on_request(uint64 id, td_api::confirmQrCodeAuthentication &request) {
CLEAN_INPUT_STRING(request.link_); CLEAN_INPUT_STRING(request.link_);
CREATE_REQUEST_PROMISE(); CREATE_REQUEST_PROMISE();
contacts_manager_->confirm_qr_code_authentication(std::move(request.link_), std::move(promise)); contacts_manager_->confirm_qr_code_authentication(request.link_, std::move(promise));
} }
void Td::on_request(uint64 id, const td_api::getCurrentState &request) { void Td::on_request(uint64 id, const td_api::getCurrentState &request) {
@ -4653,7 +4654,7 @@ void Td::on_request(uint64 id, td_api::checkRecoveryEmailAddressCode &request) {
CHECK_IS_USER(); CHECK_IS_USER();
CLEAN_INPUT_STRING(request.code_); CLEAN_INPUT_STRING(request.code_);
CREATE_REQUEST_PROMISE(); CREATE_REQUEST_PROMISE();
send_closure(password_manager_, &PasswordManager::check_recovery_email_address_code, request.code_, send_closure(password_manager_, &PasswordManager::check_recovery_email_address_code, std::move(request.code_),
std::move(promise)); std::move(promise));
} }
@ -5574,7 +5575,7 @@ void Td::on_request(uint64 id, td_api::editInlineMessageText &request) {
CHECK_IS_BOT(); CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.inline_message_id_); CLEAN_INPUT_STRING(request.inline_message_id_);
CREATE_OK_REQUEST_PROMISE(); CREATE_OK_REQUEST_PROMISE();
messages_manager_->edit_inline_message_text(std::move(request.inline_message_id_), std::move(request.reply_markup_), messages_manager_->edit_inline_message_text(request.inline_message_id_, std::move(request.reply_markup_),
std::move(request.input_message_content_), std::move(promise)); std::move(request.input_message_content_), std::move(promise));
} }
@ -5582,16 +5583,16 @@ void Td::on_request(uint64 id, td_api::editInlineMessageLiveLocation &request) {
CHECK_IS_BOT(); CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.inline_message_id_); CLEAN_INPUT_STRING(request.inline_message_id_);
CREATE_OK_REQUEST_PROMISE(); CREATE_OK_REQUEST_PROMISE();
messages_manager_->edit_inline_message_live_location( messages_manager_->edit_inline_message_live_location(request.inline_message_id_, std::move(request.reply_markup_),
std::move(request.inline_message_id_), std::move(request.reply_markup_), std::move(request.location_), std::move(request.location_), request.heading_,
request.heading_, request.proximity_alert_radius_, std::move(promise)); request.proximity_alert_radius_, std::move(promise));
} }
void Td::on_request(uint64 id, td_api::editInlineMessageMedia &request) { void Td::on_request(uint64 id, td_api::editInlineMessageMedia &request) {
CHECK_IS_BOT(); CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.inline_message_id_); CLEAN_INPUT_STRING(request.inline_message_id_);
CREATE_OK_REQUEST_PROMISE(); CREATE_OK_REQUEST_PROMISE();
messages_manager_->edit_inline_message_media(std::move(request.inline_message_id_), std::move(request.reply_markup_), messages_manager_->edit_inline_message_media(request.inline_message_id_, std::move(request.reply_markup_),
std::move(request.input_message_content_), std::move(promise)); std::move(request.input_message_content_), std::move(promise));
} }
@ -5599,17 +5600,16 @@ void Td::on_request(uint64 id, td_api::editInlineMessageCaption &request) {
CHECK_IS_BOT(); CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.inline_message_id_); CLEAN_INPUT_STRING(request.inline_message_id_);
CREATE_OK_REQUEST_PROMISE(); CREATE_OK_REQUEST_PROMISE();
messages_manager_->edit_inline_message_caption(std::move(request.inline_message_id_), messages_manager_->edit_inline_message_caption(request.inline_message_id_, std::move(request.reply_markup_),
std::move(request.reply_markup_), std::move(request.caption_), std::move(request.caption_), std::move(promise));
std::move(promise));
} }
void Td::on_request(uint64 id, td_api::editInlineMessageReplyMarkup &request) { void Td::on_request(uint64 id, td_api::editInlineMessageReplyMarkup &request) {
CHECK_IS_BOT(); CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.inline_message_id_); CLEAN_INPUT_STRING(request.inline_message_id_);
CREATE_OK_REQUEST_PROMISE(); CREATE_OK_REQUEST_PROMISE();
messages_manager_->edit_inline_message_reply_markup(std::move(request.inline_message_id_), messages_manager_->edit_inline_message_reply_markup(request.inline_message_id_, std::move(request.reply_markup_),
std::move(request.reply_markup_), std::move(promise)); std::move(promise));
} }
void Td::on_request(uint64 id, td_api::editMessageSchedulingState &request) { void Td::on_request(uint64 id, td_api::editMessageSchedulingState &request) {
@ -5630,8 +5630,8 @@ void Td::on_request(uint64 id, td_api::setInlineGameScore &request) {
CHECK_IS_BOT(); CHECK_IS_BOT();
CLEAN_INPUT_STRING(request.inline_message_id_); CLEAN_INPUT_STRING(request.inline_message_id_);
CREATE_OK_REQUEST_PROMISE(); CREATE_OK_REQUEST_PROMISE();
game_manager_->set_inline_game_score(std::move(request.inline_message_id_), request.edit_message_, game_manager_->set_inline_game_score(request.inline_message_id_, request.edit_message_, UserId(request.user_id_),
UserId(request.user_id_), request.score_, request.force_, std::move(promise)); request.score_, request.force_, std::move(promise));
} }
void Td::on_request(uint64 id, td_api::getGameHighScores &request) { void Td::on_request(uint64 id, td_api::getGameHighScores &request) {
@ -6243,8 +6243,8 @@ void Td::on_request(uint64 id, const td_api::leaveChat &request) {
} }
} }
contacts_manager_->set_dialog_participant_status( contacts_manager_->set_dialog_participant_status(
dialog_id, td_api::make_object<td_api::messageSenderUser>(contacts_manager_->get_my_id().get()), dialog_id, td_api::make_object<td_api::messageSenderUser>(contacts_manager_->get_my_id().get()), new_status,
std::move(new_status), std::move(promise)); std::move(promise));
} }
void Td::on_request(uint64 id, const td_api::addChatMember &request) { void Td::on_request(uint64 id, const td_api::addChatMember &request) {
@ -6263,8 +6263,8 @@ void Td::on_request(uint64 id, const td_api::addChatMembers &request) {
void Td::on_request(uint64 id, td_api::setChatMemberStatus &request) { void Td::on_request(uint64 id, td_api::setChatMemberStatus &request) {
CREATE_OK_REQUEST_PROMISE(); CREATE_OK_REQUEST_PROMISE();
contacts_manager_->set_dialog_participant_status(DialogId(request.chat_id_), std::move(request.member_id_), contacts_manager_->set_dialog_participant_status(DialogId(request.chat_id_), request.member_id_, request.status_,
request.status_, std::move(promise)); std::move(promise));
} }
void Td::on_request(uint64 id, const td_api::banChatMember &request) { void Td::on_request(uint64 id, const td_api::banChatMember &request) {
@ -6297,8 +6297,7 @@ void Td::on_request(uint64 id, td_api::transferChatOwnership &request) {
void Td::on_request(uint64 id, td_api::getChatMember &request) { void Td::on_request(uint64 id, td_api::getChatMember &request) {
CREATE_REQUEST_PROMISE(); CREATE_REQUEST_PROMISE();
contacts_manager_->get_dialog_participant(DialogId(request.chat_id_), std::move(request.member_id_), contacts_manager_->get_dialog_participant(DialogId(request.chat_id_), request.member_id_, std::move(promise));
std::move(promise));
} }
void Td::on_request(uint64 id, td_api::searchChatMembers &request) { void Td::on_request(uint64 id, td_api::searchChatMembers &request) {
@ -7085,7 +7084,8 @@ void Td::on_request(uint64 id, td_api::getStatisticalGraph &request) {
CHECK_IS_USER(); CHECK_IS_USER();
CLEAN_INPUT_STRING(request.token_); CLEAN_INPUT_STRING(request.token_);
CREATE_REQUEST_PROMISE(); CREATE_REQUEST_PROMISE();
contacts_manager_->load_statistics_graph(DialogId(request.chat_id_), request.token_, request.x_, std::move(promise)); contacts_manager_->load_statistics_graph(DialogId(request.chat_id_), std::move(request.token_), request.x_,
std::move(promise));
} }
void Td::on_request(uint64 id, td_api::setChatNotificationSettings &request) { void Td::on_request(uint64 id, td_api::setChatNotificationSettings &request) {
@ -7838,8 +7838,8 @@ void Td::on_request(uint64 id, td_api::sendEmailAddressVerificationCode &request
CHECK_IS_USER(); CHECK_IS_USER();
CLEAN_INPUT_STRING(request.email_address_); CLEAN_INPUT_STRING(request.email_address_);
CREATE_REQUEST_PROMISE(); CREATE_REQUEST_PROMISE();
send_closure(password_manager_, &PasswordManager::send_email_address_verification_code, request.email_address_, send_closure(password_manager_, &PasswordManager::send_email_address_verification_code,
std::move(promise)); std::move(request.email_address_), std::move(promise));
} }
void Td::on_request(uint64 id, const td_api::resendEmailAddressVerificationCode &request) { void Td::on_request(uint64 id, const td_api::resendEmailAddressVerificationCode &request) {
@ -7852,7 +7852,7 @@ void Td::on_request(uint64 id, td_api::checkEmailAddressVerificationCode &reques
CHECK_IS_USER(); CHECK_IS_USER();
CLEAN_INPUT_STRING(request.code_); CLEAN_INPUT_STRING(request.code_);
CREATE_OK_REQUEST_PROMISE(); CREATE_OK_REQUEST_PROMISE();
send_closure(password_manager_, &PasswordManager::check_email_address_verification_code, request.code_, send_closure(password_manager_, &PasswordManager::check_email_address_verification_code, std::move(request.code_),
std::move(promise)); std::move(promise));
} }
@ -8341,7 +8341,8 @@ td_api::object_ptr<td_api::Object> Td::do_static_request(const td_api::getLangua
td_api::object_ptr<td_api::Object> Td::do_static_request(const td_api::getPhoneNumberInfoSync &request) { td_api::object_ptr<td_api::Object> Td::do_static_request(const td_api::getPhoneNumberInfoSync &request) {
// don't check language_code/phone number UTF-8 correctness // don't check language_code/phone number UTF-8 correctness
return CountryInfoManager::get_phone_number_info_sync(request.language_code_, request.phone_number_prefix_); return CountryInfoManager::get_phone_number_info_sync(request.language_code_,
std::move(request.phone_number_prefix_));
} }
td_api::object_ptr<td_api::Object> Td::do_static_request(const td_api::getPushReceiverId &request) { td_api::object_ptr<td_api::Object> Td::do_static_request(const td_api::getPushReceiverId &request) {

View File

@ -337,7 +337,7 @@ class Td final : public Actor {
void on_get_terms_of_service(Result<std::pair<int32, TermsOfService>> result, bool dummy); void on_get_terms_of_service(Result<std::pair<int32, TermsOfService>> result, bool dummy);
void on_get_promo_data(Result<telegram_api::object_ptr<telegram_api::help_PromoData>> result, bool dummy); void on_get_promo_data(Result<telegram_api::object_ptr<telegram_api::help_PromoData>> r_promo_data, bool dummy);
template <class T> template <class T>
friend class RequestActor; // uses send_result/send_error friend class RequestActor; // uses send_result/send_error
@ -355,7 +355,7 @@ class Td final : public Actor {
void on_config_option_updated(const string &name); void on_config_option_updated(const string &name);
void send(NetQueryPtr &&query); static void send(NetQueryPtr &&query);
class OnRequest; class OnRequest;

View File

@ -52,7 +52,7 @@ std::string get_sqlite_path(const TdParameters &parameters) {
Result<TdDb::EncryptionInfo> check_encryption(string path) { Result<TdDb::EncryptionInfo> check_encryption(string path) {
Binlog binlog; Binlog binlog;
auto status = binlog.init(path, Binlog::Callback()); auto status = binlog.init(std::move(path), Binlog::Callback());
if (status.is_error() && status.code() != Binlog::Error::WrongPassword) { if (status.is_error() && status.code() != Binlog::Error::WrongPassword) {
LOG(WARNING) << "Failed to check binlog: " << status; LOG(WARNING) << "Failed to check binlog: " << status;
return Status::Error(400, status.message()); return Status::Error(400, status.message());
@ -281,7 +281,7 @@ void TdDb::do_close(Promise<> on_finished, bool destroy_flag) {
lock.set_value(Unit()); lock.set_value(Unit());
} }
Status TdDb::init_sqlite(int32 scheduler_id, const TdParameters &parameters, DbKey key, DbKey old_key, Status TdDb::init_sqlite(int32 scheduler_id, const TdParameters &parameters, const DbKey &key, const DbKey &old_key,
BinlogKeyValue<Binlog> &binlog_pmc) { BinlogKeyValue<Binlog> &binlog_pmc) {
CHECK(!parameters.use_message_db || parameters.use_chat_info_db); CHECK(!parameters.use_message_db || parameters.use_chat_info_db);
CHECK(!parameters.use_chat_info_db || parameters.use_file_db); CHECK(!parameters.use_chat_info_db || parameters.use_file_db);
@ -489,7 +489,7 @@ Status TdDb::destroy(const TdParameters &parameters) {
return Status::OK(); return Status::OK();
} }
void TdDb::with_db_path(std::function<void(CSlice)> callback) { void TdDb::with_db_path(const std::function<void(CSlice)> &callback) {
SqliteDb::with_db_path(sqlite_path(), callback); SqliteDb::with_db_path(sqlite_path(), callback);
callback(binlog_path()); callback(binlog_path());
} }

View File

@ -97,7 +97,7 @@ class TdDb {
void change_key(DbKey key, Promise<> promise); void change_key(DbKey key, Promise<> promise);
void with_db_path(std::function<void(CSlice)> callback); void with_db_path(const std::function<void(CSlice)> &callback);
Result<string> get_stats(); Result<string> get_stats();
@ -121,7 +121,7 @@ class TdDb {
std::shared_ptr<ConcurrentBinlog> binlog_; std::shared_ptr<ConcurrentBinlog> binlog_;
Status init(int32 scheduler_id, const TdParameters &parameters, DbKey key, Events &events); Status init(int32 scheduler_id, const TdParameters &parameters, DbKey key, Events &events);
Status init_sqlite(int32 scheduler_id, const TdParameters &parameters, DbKey key, DbKey old_key, Status init_sqlite(int32 scheduler_id, const TdParameters &parameters, const DbKey &key, const DbKey &old_key,
BinlogKeyValue<Binlog> &binlog_pmc); BinlogKeyValue<Binlog> &binlog_pmc);
void do_close(Promise<> on_finished, bool destroy_flag); void do_close(Promise<> on_finished, bool destroy_flag);

View File

@ -65,9 +65,9 @@ class AcceptTermsOfServiceQuery final : public Td::ResultHandler {
explicit AcceptTermsOfServiceQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) { explicit AcceptTermsOfServiceQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) {
} }
void send(string terms_of_service_id) { void send(const string &terms_of_service_id) {
send_query(G()->net_query_creator().create(telegram_api::help_acceptTermsOfService( send_query(G()->net_query_creator().create(telegram_api::help_acceptTermsOfService(
telegram_api::make_object<telegram_api::dataJSON>(std::move(terms_of_service_id))))); telegram_api::make_object<telegram_api::dataJSON>(terms_of_service_id))));
} }
void on_result(uint64 id, BufferSlice packet) final { void on_result(uint64 id, BufferSlice packet) final {
@ -116,7 +116,7 @@ void get_terms_of_service(Td *td, Promise<std::pair<int32, TermsOfService>> prom
} }
void accept_terms_of_service(Td *td, string &&terms_of_service_id, Promise<Unit> &&promise) { void accept_terms_of_service(Td *td, string &&terms_of_service_id, Promise<Unit> &&promise) {
td->create_handler<AcceptTermsOfServiceQuery>(std::move(promise))->send(std::move(terms_of_service_id)); td->create_handler<AcceptTermsOfServiceQuery>(std::move(promise))->send(terms_of_service_id);
} }
} // namespace td } // namespace td

View File

@ -1877,30 +1877,29 @@ void UpdatesManager::process_updates(vector<tl_object_ptr<telegram_api::Update>>
} }
} }
if (force_apply) { if (force_apply) {
// forcely process pts updates
for (auto &update : updates) { for (auto &update : updates) {
if (update != nullptr && is_pts_update(update.get())) { if (update != nullptr) {
auto constructor_id = update->get_id(); if (is_pts_update(update.get())) {
if (constructor_id == telegram_api::updateWebPage::ID) { auto constructor_id = update->get_id();
auto update_web_page = move_tl_object_as<telegram_api::updateWebPage>(update); if (constructor_id == telegram_api::updateWebPage::ID) {
td_->web_pages_manager_->on_get_web_page(std::move(update_web_page->webpage_), DialogId()); auto update_web_page = move_tl_object_as<telegram_api::updateWebPage>(update);
continue; td_->web_pages_manager_->on_get_web_page(std::move(update_web_page->webpage_), DialogId());
continue;
}
CHECK(constructor_id != telegram_api::updateFolderPeers::ID);
if (constructor_id == telegram_api::updateReadHistoryInbox::ID) {
static_cast<telegram_api::updateReadHistoryInbox *>(update.get())->still_unread_count_ = -1;
}
process_pts_update(std::move(update));
} else if (is_qts_update(update.get())) {
process_qts_update(std::move(update), 0, mpas.get_promise());
} else if (update->get_id() == telegram_api::updateChannelTooLong::ID) {
td_->messages_manager_->on_update_channel_too_long(
move_tl_object_as<telegram_api::updateChannelTooLong>(update), true);
} }
CHECK(constructor_id != telegram_api::updateFolderPeers::ID);
if (constructor_id == telegram_api::updateReadHistoryInbox::ID) {
static_cast<telegram_api::updateReadHistoryInbox *>(update.get())->still_unread_count_ = -1;
}
process_pts_update(std::move(update));
}
if (update != nullptr && is_qts_update(update.get())) {
process_qts_update(std::move(update), 0, mpas.get_promise());
}
if (update != nullptr && update->get_id() == telegram_api::updateChannelTooLong::ID) {
td_->messages_manager_->on_update_channel_too_long(
move_tl_object_as<telegram_api::updateChannelTooLong>(update), true);
} }
} }
} }
@ -2102,8 +2101,7 @@ void UpdatesManager::process_qts_update(tl_object_ptr<telegram_api::Update> &&up
} }
case telegram_api::updateBotStopped::ID: { case telegram_api::updateBotStopped::ID: {
auto update = move_tl_object_as<telegram_api::updateBotStopped>(update_ptr); auto update = move_tl_object_as<telegram_api::updateBotStopped>(update_ptr);
td_->contacts_manager_->on_update_bot_stopped(UserId(update->user_id_), update->date_, td_->contacts_manager_->on_update_bot_stopped(UserId(update->user_id_), update->date_, update->stopped_);
std::move(update->stopped_));
add_qts(qts).set_value(Unit()); add_qts(qts).set_value(Unit());
break; break;
} }

View File

@ -2228,7 +2228,7 @@ unique_ptr<WebPageBlock> get_web_page_block(Td *td, tl_object_ptr<telegram_api::
} }
case telegram_api::pageBlockMap::ID: { case telegram_api::pageBlockMap::ID: {
auto page_block = move_tl_object_as<telegram_api::pageBlockMap>(page_block_ptr); auto page_block = move_tl_object_as<telegram_api::pageBlockMap>(page_block_ptr);
Location location(std::move(page_block->geo_)); Location location(page_block->geo_);
auto zoom = page_block->zoom_; auto zoom = page_block->zoom_;
Dimensions dimensions = get_dimensions(page_block->w_, page_block->h_, "pageBlockMap"); Dimensions dimensions = get_dimensions(page_block->w_, page_block->h_, "pageBlockMap");
if (location.empty()) { if (location.empty()) {

View File

@ -1055,18 +1055,19 @@ void WebPagesManager::get_web_page_by_url(const string &url, Promise<WebPageId>
load_web_page_by_url(url, std::move(promise)); load_web_page_by_url(url, std::move(promise));
} }
void WebPagesManager::load_web_page_by_url(const string &url, Promise<WebPageId> &&promise) { void WebPagesManager::load_web_page_by_url(string url, Promise<WebPageId> &&promise) {
if (!G()->parameters().use_message_db) { if (!G()->parameters().use_message_db) {
return reload_web_page_by_url(url, std::move(promise)); return reload_web_page_by_url(url, std::move(promise));
} }
LOG(INFO) << "Load \"" << url << '"'; LOG(INFO) << "Load \"" << url << '"';
G()->td_db()->get_sqlite_pmc()->get( auto key = get_web_page_url_database_key(url);
get_web_page_url_database_key(url), G()->td_db()->get_sqlite_pmc()->get(key, PromiseCreator::lambda([actor_id = actor_id(this), url = std::move(url),
PromiseCreator::lambda([actor_id = actor_id(this), url, promise = std::move(promise)](string value) mutable { promise = std::move(promise)](string value) mutable {
send_closure(actor_id, &WebPagesManager::on_load_web_page_id_by_url_from_database, std::move(url), send_closure(actor_id,
std::move(value), std::move(promise)); &WebPagesManager::on_load_web_page_id_by_url_from_database,
})); std::move(url), std::move(value), std::move(promise));
}));
} }
void WebPagesManager::on_load_web_page_id_by_url_from_database(string url, string value, Promise<WebPageId> &&promise) { void WebPagesManager::on_load_web_page_id_by_url_from_database(string url, string value, Promise<WebPageId> &&promise) {

View File

@ -164,7 +164,7 @@ class WebPagesManager final : public Actor {
static string get_web_page_url_database_key(const string &url); static string get_web_page_url_database_key(const string &url);
void load_web_page_by_url(const string &url, Promise<WebPageId> &&promise); void load_web_page_by_url(string url, Promise<WebPageId> &&promise);
void on_load_web_page_id_by_url_from_database(string url, string value, Promise<WebPageId> &&promise); void on_load_web_page_id_by_url_from_database(string url, string value, Promise<WebPageId> &&promise);

Some files were not shown because too many files have changed in this diff Show More