Remove Telegram C-Backend.

This commit is contained in:
B. Petersen
2016-11-13 20:46:09 +01:00
parent d904ee6fff
commit 93eda8922c
70 changed files with 189 additions and 13818 deletions
+1 -36
View File
@@ -956,40 +956,6 @@ LOCAL_SRC_FILES := \
include $(BUILD_STATIC_LIBRARY)
################################################################################
# tgnet
################################################################################
include $(CLEAR_VARS)
LOCAL_CPPFLAGS := -Wall -std=c++11 -DANDROID -frtti -DHAVE_PTHREAD -finline-functions -ffast-math -Os
LOCAL_C_INCLUDES += $(LOCAL_PATH)/openssl/include/
LOCAL_ARM_MODE := arm
LOCAL_MODULE := tgnet
LOCAL_STATIC_LIBRARIES := crypto
LOCAL_SRC_FILES := \
./tgnet/BuffersStorage.cpp \
./tgnet/ByteArray.cpp \
./tgnet/ByteStream.cpp \
./tgnet/Connection.cpp \
./tgnet/ConnectionSession.cpp \
./tgnet/ConnectionsManager.cpp \
./tgnet/ConnectionSocket.cpp \
./tgnet/Datacenter.cpp \
./tgnet/EventObject.cpp \
./tgnet/FileLog.cpp \
./tgnet/MTProtoScheme.cpp \
./tgnet/NativeByteBuffer.cpp \
./tgnet/Request.cpp \
./tgnet/Timer.cpp \
./tgnet/TLObject.cpp \
./tgnet/Config.cpp
include $(BUILD_STATIC_LIBRARY)
################################################################################
# webp
################################################################################
@@ -1347,7 +1313,7 @@ LOCAL_CFLAGS += -Drestrict='' -D__EMX__ -DOPUS_BUILD -DFIXED_POINT -DUSE_ALLOCA
LOCAL_CFLAGS += -DANDROID_NDK -DDISABLE_IMPORTGL -fno-strict-aliasing -fprefetch-loop-arrays -DAVOID_TABLES -DANDROID_TILE_BASED_DECODE -DANDROID_ARMV6_IDCT -ffast-math -D__STDC_CONSTANT_MACROS
LOCAL_CPPFLAGS := -DBSD=1 -ffast-math -Os -funroll-loops -std=c++11
LOCAL_LDLIBS := -ljnigraphics -llog -lz -latomic
LOCAL_STATIC_LIBRARIES := etpan sasl2 webp sqlite tgnet breakpad avformat avcodec avutil libiconv
LOCAL_STATIC_LIBRARIES := etpan sasl2 webp sqlite crypto breakpad avformat avcodec avutil libiconv
# if you get "undefined reference" errors, the reason for this may be the _order_! Eg. libiconv as the first library does not work!
LOCAL_SRC_FILES := \
@@ -1637,7 +1603,6 @@ LOCAL_SRC_FILES += \
./image.c \
./video.c \
./gifvideo.cpp \
./TgNetWrapper.cpp \
../../../messenger-backend/src/mrchat.c \
../../../messenger-backend/src/mrchatlist.c \
../../../messenger-backend/src/mrcontact.c \
-336
View File
@@ -1,336 +0,0 @@
#include <jni.h>
#include "tgnet/BuffersStorage.h"
#include "tgnet/NativeByteBuffer.h"
#include "tgnet/ConnectionsManager.h"
#include "tgnet/MTProtoScheme.h"
#include "tgnet/FileLog.h"
JavaVM *java;
jclass jclass_RequestDelegateInternal;
jmethodID jclass_RequestDelegateInternal_run;
jclass jclass_QuickAckDelegate;
jmethodID jclass_QuickAckDelegate_run;
jclass jclass_ConnectionsManager;
jmethodID jclass_ConnectionsManager_onUnparsedMessageReceived;
jmethodID jclass_ConnectionsManager_onUpdate;
jmethodID jclass_ConnectionsManager_onSessionCreated;
jmethodID jclass_ConnectionsManager_onLogout;
jmethodID jclass_ConnectionsManager_onConnectionStateChanged;
jmethodID jclass_ConnectionsManager_onInternalPushReceived;
jmethodID jclass_ConnectionsManager_onUpdateConfig;
jint getFreeBuffer(JNIEnv *env, jclass c, jint length) {
return (jint) BuffersStorage::getInstance().getFreeBuffer(length);
}
jint limit(JNIEnv *env, jclass c, jint address) {
NativeByteBuffer *buffer = (NativeByteBuffer *) address;
return buffer->limit();
}
jint position(JNIEnv *env, jclass c, jint address) {
NativeByteBuffer *buffer = (NativeByteBuffer *) address;
return buffer->position();
}
void reuse(JNIEnv *env, jclass c, jint address) {
NativeByteBuffer *buffer = (NativeByteBuffer *) address;
buffer->reuse();
}
jobject getJavaByteBuffer(JNIEnv *env, jclass c, jint address) {
NativeByteBuffer *buffer = (NativeByteBuffer *) address;
return buffer->getJavaByteBuffer();
}
static const char *NativeByteBufferClassPathName = "org/telegram/tgnet/NativeByteBuffer";
static JNINativeMethod NativeByteBufferMethods[] = {
{"native_getFreeBuffer", "(I)I", (void *) getFreeBuffer},
{"native_limit", "(I)I", (void *) limit},
{"native_position", "(I)I", (void *) position},
{"native_reuse", "(I)V", (void *) reuse},
{"native_getJavaByteBuffer", "(I)Ljava/nio/ByteBuffer;", (void *) getJavaByteBuffer}
};
jlong getCurrentTimeMillis(JNIEnv *env, jclass c) {
return ConnectionsManager::getInstance().getCurrentTimeMillis();
}
jint getCurrentTime(JNIEnv *env, jclass c) {
return ConnectionsManager::getInstance().getCurrentTime();
}
jint getTimeDifference(JNIEnv *env, jclass c) {
return ConnectionsManager::getInstance().getTimeDifference();
}
void sendRequest(JNIEnv *env, jclass c, jint object, jobject onComplete, jobject onQuickAck, jint flags, jint datacenterId, jint connetionType, jboolean immediate, jint token) {
TL_api_request *request = new TL_api_request();
request->request = (NativeByteBuffer *) object;
if (onComplete != nullptr) {
onComplete = env->NewGlobalRef(onComplete);
}
if (onQuickAck != nullptr) {
onQuickAck = env->NewGlobalRef(onQuickAck);
}
ConnectionsManager::getInstance().sendRequest(request, ([onComplete](TLObject *response, TL_error *error) {
TL_api_response *resp = (TL_api_response *) response;
jint ptr = 0;
jint errorCode = 0;
jstring errorText = nullptr;
if (resp != nullptr) {
ptr = (jint) resp->response.get();
} else if (error != nullptr) {
errorCode = error->code;
errorText = jniEnv->NewStringUTF(error->text.c_str());
}
if (onComplete != nullptr) {
jniEnv->CallVoidMethod(onComplete, jclass_RequestDelegateInternal_run, ptr, errorCode, errorText);
}
if (errorText != nullptr) {
jniEnv->DeleteLocalRef(errorText);
}
}), ([onQuickAck] {
if (onQuickAck != nullptr) {
jniEnv->CallVoidMethod(onQuickAck, jclass_QuickAckDelegate_run);
}
}), flags, datacenterId, (ConnectionType) connetionType, immediate, token, onComplete, onQuickAck);
}
void cancelRequest(JNIEnv *env, jclass c, jint token, jboolean notifyServer) {
return ConnectionsManager::getInstance().cancelRequest(token, notifyServer);
}
void cleanUp(JNIEnv *env, jclass c) {
return ConnectionsManager::getInstance().cleanUp();
}
void cancelRequestsForGuid(JNIEnv *env, jclass c, jint guid) {
return ConnectionsManager::getInstance().cancelRequestsForGuid(guid);
}
void bindRequestToGuid(JNIEnv *env, jclass c, jint requestToken, jint guid) {
return ConnectionsManager::getInstance().bindRequestToGuid(requestToken, guid);
}
void applyDatacenterAddress(JNIEnv *env, jclass c, jint datacenterId, jstring ipAddress, jint port) {
const char *valueStr = env->GetStringUTFChars(ipAddress, 0);
ConnectionsManager::getInstance().applyDatacenterAddress(datacenterId, std::string(valueStr), port);
if (valueStr != 0) {
env->ReleaseStringUTFChars(ipAddress, valueStr);
}
}
jint getConnectionState(JNIEnv *env, jclass c) {
return ConnectionsManager::getInstance().getConnectionState();
}
void setUserId(JNIEnv *env, jclass c, int32_t id) {
ConnectionsManager::getInstance().setUserId(id);
}
void switchBackend(JNIEnv *env, jclass c) {
ConnectionsManager::getInstance().switchBackend();
}
void pauseNetwork(JNIEnv *env, jclass c) {
ConnectionsManager::getInstance().pauseNetwork();
}
void resumeNetwork(JNIEnv *env, jclass c, jboolean partial) {
ConnectionsManager::getInstance().resumeNetwork(partial);
}
void updateDcSettings(JNIEnv *env, jclass c) {
ConnectionsManager::getInstance().updateDcSettings(0);
}
void setUseIpv6(JNIEnv *env, jclass c, bool value) {
ConnectionsManager::getInstance().setUseIpv6(value);
}
void setNetworkAvailable(JNIEnv *env, jclass c, jboolean value) {
ConnectionsManager::getInstance().setNetworkAvailable(value);
}
void setPushConnectionEnabled(JNIEnv *env, jclass c, jboolean value) {
ConnectionsManager::getInstance().setPushConnectionEnabled(value);
}
class Delegate : public ConnectiosManagerDelegate {
void onUpdate() {
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onUpdate);
}
void onSessionCreated() {
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onSessionCreated);
}
void onConnectionStateChanged(ConnectionState state) {
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onConnectionStateChanged, state);
}
void onUnparsedMessageReceived(int64_t reqMessageId, NativeByteBuffer *buffer, ConnectionType connectionType) {
if (connectionType == ConnectionTypeGeneric) {
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onUnparsedMessageReceived, buffer);
}
}
void onLogout() {
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onLogout);
}
void onUpdateConfig(TL_config *config) {
NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(config->getObjectSize());
config->serializeToStream(buffer);
buffer->position(0);
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onUpdateConfig, buffer);
buffer->reuse();
}
void onInternalPushReceived() {
jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onInternalPushReceived);
}
};
void init(JNIEnv *env, jclass c, jint version, jint layer, jint apiId, jstring deviceModel, jstring systemVersion, jstring appVersion, jstring langCode, jstring configPath, jstring logPath, jint userId, jboolean enablePushConnection) {
const char *deviceModelStr = env->GetStringUTFChars(deviceModel, 0);
const char *systemVersionStr = env->GetStringUTFChars(systemVersion, 0);
const char *appVersionStr = env->GetStringUTFChars(appVersion, 0);
const char *langCodeStr = env->GetStringUTFChars(langCode, 0);
const char *configPathStr = env->GetStringUTFChars(configPath, 0);
const char *logPathStr = env->GetStringUTFChars(logPath, 0);
ConnectionsManager::getInstance().init(version, layer, apiId, std::string(deviceModelStr), std::string(systemVersionStr), std::string(appVersionStr), std::string(langCodeStr), std::string(configPathStr), std::string(logPathStr), userId, true, enablePushConnection);
if (deviceModelStr != 0) {
env->ReleaseStringUTFChars(deviceModel, deviceModelStr);
}
if (systemVersionStr != 0) {
env->ReleaseStringUTFChars(systemVersion, systemVersionStr);
}
if (appVersionStr != 0) {
env->ReleaseStringUTFChars(appVersion, appVersionStr);
}
if (langCodeStr != 0) {
env->ReleaseStringUTFChars(langCode, langCodeStr);
}
if (configPathStr != 0) {
env->ReleaseStringUTFChars(configPath, configPathStr);
}
if (logPathStr != 0) {
env->ReleaseStringUTFChars(logPath, logPathStr);
}
}
void setJava(JNIEnv *env, jclass c, jboolean useJavaByteBuffers) {
ConnectionsManager::useJavaVM(java, useJavaByteBuffers);
ConnectionsManager::getInstance().setDelegate(new Delegate());
}
static const char *ConnectionsManagerClassPathName = "org/telegram/tgnet/ConnectionsManager";
static JNINativeMethod ConnectionsManagerMethods[] = {
{"native_getCurrentTimeMillis", "()J", (void *) getCurrentTimeMillis},
{"native_getCurrentTime", "()I", (void *) getCurrentTime},
{"native_getTimeDifference", "()I", (void *) getTimeDifference},
{"native_sendRequest", "(ILorg/telegram/tgnet/RequestDelegateInternal;Lorg/telegram/tgnet/QuickAckDelegate;IIIZI)V", (void *) sendRequest},
{"native_cancelRequest", "(IZ)V", (void *) cancelRequest},
{"native_cleanUp", "()V", (void *) cleanUp},
{"native_cancelRequestsForGuid", "(I)V", (void *) cancelRequestsForGuid},
{"native_bindRequestToGuid", "(II)V", (void *) bindRequestToGuid},
{"native_applyDatacenterAddress", "(ILjava/lang/String;I)V", (void *) applyDatacenterAddress},
{"native_getConnectionState", "()I", (void *) getConnectionState},
{"native_setUserId", "(I)V", (void *) setUserId},
{"native_init", "(IIILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZ)V", (void *) init},
{"native_switchBackend", "()V", (void *) switchBackend},
{"native_pauseNetwork", "()V", (void *) pauseNetwork},
{"native_resumeNetwork", "(Z)V", (void *) resumeNetwork},
{"native_updateDcSettings", "()V", (void *) updateDcSettings},
{"native_setUseIpv6", "(Z)V", (void *) setUseIpv6},
{"native_setNetworkAvailable", "(Z)V", (void *) setNetworkAvailable},
{"native_setPushConnectionEnabled", "(Z)V", (void *) setPushConnectionEnabled},
{"native_setJava", "(Z)V", (void *) setJava}
};
inline int registerNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int methodsCount) {
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, methods, methodsCount) < 0) {
return JNI_FALSE;
}
return JNI_TRUE;
}
extern "C" int registerNativeTgNetFunctions(JavaVM *vm, JNIEnv *env) {
java = vm;
if (!registerNativeMethods(env, NativeByteBufferClassPathName, NativeByteBufferMethods, sizeof(NativeByteBufferMethods) / sizeof(NativeByteBufferMethods[0]))) {
return JNI_FALSE;
}
if (!registerNativeMethods(env, ConnectionsManagerClassPathName, ConnectionsManagerMethods, sizeof(ConnectionsManagerMethods) / sizeof(ConnectionsManagerMethods[0]))) {
return JNI_FALSE;
}
jclass_RequestDelegateInternal = (jclass) env->NewGlobalRef(env->FindClass("org/telegram/tgnet/RequestDelegateInternal"));
if (jclass_RequestDelegateInternal == 0) {
return JNI_FALSE;
}
jclass_RequestDelegateInternal_run = env->GetMethodID(jclass_RequestDelegateInternal, "run", "(IILjava/lang/String;)V");
if (jclass_RequestDelegateInternal_run == 0) {
return JNI_FALSE;
}
jclass_QuickAckDelegate = (jclass) env->NewGlobalRef(env->FindClass("org/telegram/tgnet/QuickAckDelegate"));
if (jclass_RequestDelegateInternal == 0) {
return JNI_FALSE;
}
jclass_QuickAckDelegate_run = env->GetMethodID(jclass_QuickAckDelegate, "run", "()V");
if (jclass_QuickAckDelegate_run == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager = (jclass) env->NewGlobalRef(env->FindClass("org/telegram/tgnet/ConnectionsManager"));
if (jclass_ConnectionsManager == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onUnparsedMessageReceived = env->GetStaticMethodID(jclass_ConnectionsManager, "onUnparsedMessageReceived", "(I)V");
if (jclass_ConnectionsManager_onUnparsedMessageReceived == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onUpdate = env->GetStaticMethodID(jclass_ConnectionsManager, "onUpdate", "()V");
if (jclass_ConnectionsManager_onUpdate == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onSessionCreated = env->GetStaticMethodID(jclass_ConnectionsManager, "onSessionCreated", "()V");
if (jclass_ConnectionsManager_onSessionCreated == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onLogout = env->GetStaticMethodID(jclass_ConnectionsManager, "onLogout", "()V");
if (jclass_ConnectionsManager_onLogout == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onConnectionStateChanged = env->GetStaticMethodID(jclass_ConnectionsManager, "onConnectionStateChanged", "(I)V");
if (jclass_ConnectionsManager_onConnectionStateChanged == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onInternalPushReceived = env->GetStaticMethodID(jclass_ConnectionsManager, "onInternalPushReceived", "()V");
if (jclass_ConnectionsManager_onInternalPushReceived == 0) {
return JNI_FALSE;
}
jclass_ConnectionsManager_onUpdateConfig = env->GetStaticMethodID(jclass_ConnectionsManager, "onUpdateConfig", "(I)V");
if (jclass_ConnectionsManager_onUpdateConfig == 0) {
return JNI_FALSE;
}
ConnectionsManager::getInstance().setDelegate(new Delegate());
return JNI_TRUE;
}
+5 -1
View File
@@ -9,7 +9,7 @@
#include "utils.h"
#include "image.h"
int registerNativeTgNetFunctions(JavaVM *vm, JNIEnv *env);
//int registerNativeTgNetFunctions(JavaVM *vm, JNIEnv *env);
int gifvideoOnJNILoad(JavaVM *vm, JNIEnv *env);
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
@@ -28,9 +28,11 @@ jint JNI_OnLoad(JavaVM *vm, void *reserved) {
return -1;
}
/*
if (registerNativeTgNetFunctions(vm, env) != JNI_TRUE) {
return -1;
}
*/
return JNI_VERSION_1_6;
}
@@ -39,6 +41,7 @@ void JNI_OnUnload(JavaVM *vm, void *reserved) {
}
/*
JNIEXPORT void Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIEnv *env, jclass class, jobject buffer, jbyteArray key, jbyteArray iv, jboolean encrypt, int offset, int length) {
jbyte *what = (*env)->GetDirectBufferAddress(env, buffer) + offset;
unsigned char *keyBuff = (unsigned char *)(*env)->GetByteArrayElements(env, key, NULL);
@@ -55,6 +58,7 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIEnv *en
(*env)->ReleaseByteArrayElements(env, key, keyBuff, JNI_ABORT);
(*env)->ReleaseByteArrayElements(env, iv, ivBuff, 0);
}
*/
JNIEXPORT jstring Java_org_telegram_messenger_Utilities_readlink(JNIEnv *env, jclass class, jstring path) {
static char buf[1000];
+9
View File
@@ -674,5 +674,14 @@ JNIEXPORT jstring Java_org_telegram_messenger_MrMailbox_MrGetVersionStr(JNIEnv *
}
#include <time.h>
JNIEXPORT jlong Java_org_telegram_messenger_MrMailbox_getCurrentTimeMillis(JNIEnv *env, jclass c) {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return (jlong) ts.tv_sec * 1000 + (int64_t) ts.tv_nsec / 1000000;
}
JNIEXPORT jint Java_org_telegram_messenger_MrMailbox_getCurrentTime(JNIEnv *env, jclass c) {
return (jint) (Java_org_telegram_messenger_MrMailbox_getCurrentTimeMillis(env, c) / 1000);
}
-123
View File
@@ -1,123 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#include "BuffersStorage.h"
#include "FileLog.h"
#include "NativeByteBuffer.h"
BuffersStorage &BuffersStorage::getInstance() {
static BuffersStorage instance(true);
return instance;
}
BuffersStorage::BuffersStorage(bool threadSafe) {
isThreadSafe = threadSafe;
if (isThreadSafe) {
pthread_mutex_init(&mutex, NULL);
}
for (uint32_t a = 0; a < 4; a++) {
freeBuffers8.push_back(new NativeByteBuffer((uint32_t) 8));
}
for (uint32_t a = 0; a < 5; a++) {
freeBuffers128.push_back(new NativeByteBuffer((uint32_t) 128));
}
}
NativeByteBuffer *BuffersStorage::getFreeBuffer(uint32_t size) {
uint32_t byteCount = 0;
std::vector<NativeByteBuffer *> *arrayToGetFrom = nullptr;
NativeByteBuffer *buffer = nullptr;
if (size <= 8) {
arrayToGetFrom = &freeBuffers8;
byteCount = 8;
} else if (size <= 128) {
arrayToGetFrom = &freeBuffers128;
byteCount = 128;
} else if (size <= 1024 + 200) {
arrayToGetFrom = &freeBuffers1024;
byteCount = 1024 + 200;
} else if (size <= 4096 + 200) {
arrayToGetFrom = &freeBuffers4096;
byteCount = 4096 + 200;
} else if (size <= 16384 + 200) {
arrayToGetFrom = &freeBuffers16384;
byteCount = 16384 + 200;
} else if (size <= 40000) {
arrayToGetFrom = &freeBuffers32768;
byteCount = 40000;
} else if (size <= 160000) {
arrayToGetFrom = &freeBuffersBig;
byteCount = 160000;
} else {
buffer = new NativeByteBuffer(size);
}
if (arrayToGetFrom != nullptr) {
if (isThreadSafe) {
pthread_mutex_lock(&mutex);
}
if (arrayToGetFrom->size() > 0) {
buffer = (*arrayToGetFrom)[0];
arrayToGetFrom->erase(arrayToGetFrom->begin());
}
if (isThreadSafe) {
pthread_mutex_unlock(&mutex);
}
if (buffer == nullptr) {
buffer = new NativeByteBuffer(byteCount);
DEBUG_D("create new %u buffer", byteCount);
}
}
if (buffer != nullptr) {
buffer->limit(size);
buffer->rewind();
}
return buffer;
}
void BuffersStorage::reuseFreeBuffer(NativeByteBuffer *buffer) {
if (buffer == nullptr) {
return;
}
std::vector<NativeByteBuffer *> *arrayToReuse = nullptr;
uint32_t capacity = buffer->capacity();
uint32_t maxCount = 10;
if (capacity == 8) {
arrayToReuse = &freeBuffers8;
maxCount = 80;
} else if (capacity == 128) {
arrayToReuse = &freeBuffers128;
maxCount = 80;
} else if (capacity == 1024 + 200) {
arrayToReuse = &freeBuffers1024;
} else if (capacity == 4096 + 200) {
arrayToReuse = &freeBuffers4096;
} else if (capacity == 16384 + 200) {
arrayToReuse = &freeBuffers16384;
} else if (capacity == 40000) {
arrayToReuse = &freeBuffers32768;
} else if (capacity == 160000) {
arrayToReuse = &freeBuffersBig;
}
if (arrayToReuse != nullptr) {
if (isThreadSafe) {
pthread_mutex_lock(&mutex);
}
if (arrayToReuse->size() < maxCount) {
arrayToReuse->push_back(buffer);
} else {
DEBUG_D("too more %d buffers", capacity);
delete buffer;
}
if (isThreadSafe) {
pthread_mutex_unlock(&mutex);
}
} else {
delete buffer;
}
}
-38
View File
@@ -1,38 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef BUFFERSSTORAGE_H
#define BUFFERSSTORAGE_H
#include <vector>
#include <pthread.h>
#include <stdint.h>
class NativeByteBuffer;
class BuffersStorage {
public:
BuffersStorage(bool threadSafe);
NativeByteBuffer *getFreeBuffer(uint32_t size);
void reuseFreeBuffer(NativeByteBuffer *buffer);
static BuffersStorage &getInstance();
private:
std::vector<NativeByteBuffer *> freeBuffers8;
std::vector<NativeByteBuffer *> freeBuffers128;
std::vector<NativeByteBuffer *> freeBuffers1024;
std::vector<NativeByteBuffer *> freeBuffers4096;
std::vector<NativeByteBuffer *> freeBuffers16384;
std::vector<NativeByteBuffer *> freeBuffers32768;
std::vector<NativeByteBuffer *> freeBuffersBig;
bool isThreadSafe = true;
pthread_mutex_t mutex;
};
#endif
-71
View File
@@ -1,71 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#include <stdlib.h>
#include <memory.h>
#include "ByteArray.h"
#include "FileLog.h"
ByteArray::ByteArray() {
bytes = nullptr;
length = 0;
}
ByteArray::ByteArray(uint32_t len) {
bytes = new uint8_t[len];
if (bytes == nullptr) {
DEBUG_E("unable to allocate byte buffer %u", len);
exit(1);
}
length = len;
}
ByteArray::ByteArray(ByteArray *byteArray) {
bytes = new uint8_t[byteArray->length];
if (bytes == nullptr) {
DEBUG_E("unable to allocate byte buffer %u", byteArray->length);
exit(1);
}
length = byteArray->length;
memcpy(bytes, byteArray->bytes, length);
}
ByteArray::ByteArray(uint8_t *buffer, uint32_t len) {
bytes = new uint8_t[len];
if (bytes == nullptr) {
DEBUG_E("unable to allocate byte buffer %u", len);
exit(1);
}
length = len;
memcpy(bytes, buffer, length);
}
ByteArray::~ByteArray() {
if (bytes != nullptr) {
delete[] bytes;
bytes = nullptr;
}
}
void ByteArray::alloc(uint32_t len) {
if (bytes != nullptr) {
delete[] bytes;
bytes = nullptr;
}
bytes = new uint8_t[len];
if (bytes == nullptr) {
DEBUG_E("unable to allocate byte buffer %u", len);
exit(1);
}
length = len;
}
bool ByteArray::isEqualTo(ByteArray *byteArray) {
return byteArray->length == length && !memcmp(byteArray->bytes, bytes, length);
}
-31
View File
@@ -1,31 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef BYTEARRAY_H
#define BYTEARRAY_H
#include <stdint.h>
class ByteArray {
public:
ByteArray();
ByteArray(uint32_t len);
ByteArray(ByteArray *byteArray);
ByteArray(uint8_t *buffer, uint32_t len);
~ByteArray();
void alloc(uint32_t len);
uint32_t length;
uint8_t *bytes;
bool isEqualTo(ByteArray *byteArray);
};
#endif
-83
View File
@@ -1,83 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#include "ByteStream.h"
#include "NativeByteBuffer.h"
ByteStream::ByteStream() {
}
ByteStream::~ByteStream() {
}
void ByteStream::append(NativeByteBuffer *buffer) {
if (buffer == nullptr) {
return;
}
buffersQueue.push_back(buffer);
}
bool ByteStream::hasData() {
size_t size = buffersQueue.size();
for (uint32_t a = 0; a < size; a++) {
if (buffersQueue[a]->hasRemaining()) {
return true;
}
}
return false;
}
void ByteStream::get(NativeByteBuffer *dst) {
if (dst == nullptr) {
return;
}
size_t size = buffersQueue.size();
NativeByteBuffer *buffer;
for (uint32_t a = 0; a < size; a++) {
buffer = buffersQueue[a];
if (buffer->remaining() > dst->remaining()) {
dst->writeBytes(buffer->bytes(), buffer->position(), dst->remaining());
break;
}
dst->writeBytes(buffer->bytes(), buffer->position(), buffer->remaining());
if (!dst->hasRemaining()) {
break;
}
}
}
void ByteStream::discard(uint32_t count) {
uint32_t remaining;
NativeByteBuffer *buffer;
while (count > 0) {
buffer = buffersQueue[0];
remaining = buffer->remaining();
if (count < remaining) {
buffer->position(buffer->position() + count);
break;
}
buffer->reuse();
buffersQueue.erase(buffersQueue.begin());
count -= remaining;
}
}
void ByteStream::clean() {
if (buffersQueue.empty()) {
return;
}
size_t size = buffersQueue.size();
for (uint32_t a = 0; a < size; a++) {
NativeByteBuffer *buffer = buffersQueue[a];
buffer->reuse();
}
buffersQueue.clear();
}
-32
View File
@@ -1,32 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef BYTESTREAM_H
#define BYTESTREAM_H
#include <vector>
#include <stdint.h>
class NativeByteBuffer;
class ByteStream {
public:
ByteStream();
~ByteStream();
void append(NativeByteBuffer *buffer);
bool hasData();
void get(NativeByteBuffer *dst);
void discard(uint32_t count);
void clean();
private:
std::vector<NativeByteBuffer *> buffersQueue;
};
#endif
-125
View File
@@ -1,125 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#include <sys/stat.h>
#include <unistd.h>
#include "Config.h"
#include "ConnectionsManager.h"
#include "FileLog.h"
#include "BuffersStorage.h"
Config::Config(std::string fileName) {
configPath = ConnectionsManager::getInstance().currentConfigPath + fileName;
backupPath = configPath + ".bak";
FILE *backup = fopen(backupPath.c_str(), "rb");
if (backup != nullptr) {
DEBUG_D("Config(%p, %s) backup file found %s", this, configPath.c_str(), backupPath.c_str());
fclose(backup);
remove(configPath.c_str());
rename(backupPath.c_str(), configPath.c_str());
}
}
NativeByteBuffer *Config::readConfig() {
NativeByteBuffer *buffer = nullptr;
FILE *file = fopen(configPath.c_str(), "rb");
if (file != nullptr) {
fseek(file, 0, SEEK_END);
long fileSize = ftell(file);
if (fseek(file, 0, SEEK_SET)) {
DEBUG_E("Config(%p, %s) failed fseek to begin, reopen it", this, configPath.c_str());
fclose(file);
file = fopen(configPath.c_str(), "rb");
}
uint32_t size = 0;
int bytesRead = fread(&size, sizeof(uint32_t), 1, file);
DEBUG_D("Config(%p, %s) load, size = %u, fileSize = %u", this, configPath.c_str(), size, (uint32_t) fileSize);
if (bytesRead > 0 && size > 0 && (int32_t) size < fileSize) {
buffer = BuffersStorage::getInstance().getFreeBuffer(size);
if (fread(buffer->bytes(), sizeof(uint8_t), size, file) != size) {
buffer->reuse();
buffer = nullptr;
}
}
fclose(file);
}
return buffer;
}
void Config::writeConfig(NativeByteBuffer *buffer) {
DEBUG_D("Config(%p, %s) start write config", this, configPath.c_str());
FILE *file = fopen(configPath.c_str(), "rb");
FILE *backup = fopen(backupPath.c_str(), "rb");
bool error = false;
if (file != nullptr) {
if (backup == nullptr) {
fclose(file);
if (rename(configPath.c_str(), backupPath.c_str()) != 0) {
DEBUG_E("Config(%p) unable to rename file %s to backup file %s", this, configPath.c_str(), backupPath.c_str());
error = true;
}
} else {
fclose(file);
fclose(backup);
remove(configPath.c_str());
}
}
if (error) {
return;
}
file = fopen(configPath.c_str(), "wb");
if (chmod(configPath.c_str(), 0660)) {
DEBUG_E("Config(%p, %s) chmod failed", this, configPath.c_str());
}
if (file == nullptr) {
DEBUG_E("Config(%p, %s) unable to open file for writing", this, configPath.c_str());
return;
}
uint32_t size = buffer->position();
if (fwrite(&size, sizeof(uint32_t), 1, file) == 1) {
if (fwrite(buffer->bytes(), sizeof(uint8_t), size, file) != size) {
DEBUG_E("Config(%p, %s) failed to write config data to file", this, configPath.c_str());
error = true;
}
} else {
DEBUG_E("Config(%p, %s) failed to write config size to file", this, configPath.c_str());
error = true;
}
if (fflush(file)) {
DEBUG_E("Config(%p, %s) fflush failed", this, configPath.c_str());
error = true;
}
int fd = fileno(file);
if (fd == -1) {
DEBUG_E("Config(%p, %s) fileno failed", this, configPath.c_str());
error = true;
} else {
DEBUG_D("Config(%p, %s) fileno = %d", this, configPath.c_str(), fd);
}
if (fd != -1 && fsync(fd) == -1) {
DEBUG_E("Config(%p, %s) fsync failed", this, configPath.c_str());
error = true;
}
if (fclose(file)) {
DEBUG_E("Config(%p, %s) fclose failed", this, configPath.c_str());
error = true;
}
if (error) {
DEBUG_E("Config(%p, %s) failed to write config", this, configPath.c_str());
if (remove(configPath.c_str())) {
DEBUG_E("Config(%p, %s) remove config failed", this, configPath.c_str());
}
} else {
if (remove(backupPath.c_str())) {
DEBUG_E("Config(%p, %s) remove backup failed failed", this, configPath.c_str());
}
}
if (!error) {
DEBUG_D("Config(%p, %s) config write ok", this, configPath.c_str());
}
}
-28
View File
@@ -1,28 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef CONFIG_H
#define CONFIG_H
#include <string>
#include "NativeByteBuffer.h"
class Config {
public:
Config(std::string fileName);
NativeByteBuffer *readConfig();
void writeConfig(NativeByteBuffer *buffer);
private:
std::string configPath;
std::string backupPath;
};
#endif
-438
View File
@@ -1,438 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#include <openssl/rand.h>
#include <stdlib.h>
#include "Connection.h"
#include "ConnectionsManager.h"
#include "BuffersStorage.h"
#include "FileLog.h"
#include "Timer.h"
#include "Datacenter.h"
#include "NativeByteBuffer.h"
static uint32_t lastConnectionToken = 1;
Connection::Connection(Datacenter *datacenter, ConnectionType type) {
currentDatacenter = datacenter;
connectionType = type;
genereateNewSessionId();
connectionState = TcpConnectionStageIdle;
reconnectTimer = new Timer([&] {
reconnectTimer->stop();
connect();
});
}
Connection::~Connection() {
if (reconnectTimer != nullptr) {
reconnectTimer->stop();
delete reconnectTimer;
reconnectTimer = nullptr;
}
}
void Connection::suspendConnection() {
reconnectTimer->stop();
if (connectionState == TcpConnectionStageIdle || connectionState == TcpConnectionStageSuspended) {
return;
}
DEBUG_D("connection(%p, dc%u, type %d) suspend", this, currentDatacenter->getDatacenterId(), connectionType);
connectionState = TcpConnectionStageSuspended;
dropConnection();
ConnectionsManager::getInstance().onConnectionClosed(this);
firstPacketSent = false;
if (restOfTheData != nullptr) {
restOfTheData->reuse();
restOfTheData = nullptr;
}
lastPacketLength = 0;
connectionToken = 0;
wasConnected = false;
}
void Connection::onReceivedData(NativeByteBuffer *buffer) {
AES_ctr128_encrypt(buffer->bytes(), buffer->bytes(), buffer->limit(), &decryptKey, decryptIv, decryptCount, &decryptNum);
failedConnectionCount = 0;
NativeByteBuffer *parseLaterBuffer = nullptr;
if (restOfTheData != nullptr) {
if (lastPacketLength == 0) {
if (restOfTheData->capacity() - restOfTheData->position() >= buffer->limit()) {
restOfTheData->limit(restOfTheData->position() + buffer->limit());
restOfTheData->writeBytes(buffer);
buffer = restOfTheData;
} else {
NativeByteBuffer *newBuffer = BuffersStorage::getInstance().getFreeBuffer(restOfTheData->limit() + buffer->limit());
restOfTheData->rewind();
newBuffer->writeBytes(restOfTheData);
newBuffer->writeBytes(buffer);
buffer = newBuffer;
restOfTheData->reuse();
restOfTheData = newBuffer;
}
} else {
uint32_t len;
if (lastPacketLength - restOfTheData->position() <= buffer->limit()) {
len = lastPacketLength - restOfTheData->position();
} else {
len = buffer->limit();
}
uint32_t oldLimit = buffer->limit();
buffer->limit(len);
restOfTheData->writeBytes(buffer);
buffer->limit(oldLimit);
if (restOfTheData->position() == lastPacketLength) {
parseLaterBuffer = buffer->hasRemaining() ? buffer : nullptr;
buffer = restOfTheData;
} else {
return;
}
}
}
buffer->rewind();
while (buffer->hasRemaining()) {
if (!hasSomeDataSinceLastConnect) {
currentDatacenter->storeCurrentAddressAndPortNum();
isTryingNextPort = false;
if (connectionType == ConnectionTypePush) {
setTimeout(60 * 15);
} else {
setTimeout(25);
}
}
hasSomeDataSinceLastConnect = true;
uint32_t currentPacketLength = 0;
uint32_t mark = buffer->position();
uint8_t fByte = buffer->readByte(nullptr);
if ((fByte & (1 << 7)) != 0) {
buffer->position(mark);
if (buffer->remaining() < 4) {
NativeByteBuffer *reuseLater = restOfTheData;
restOfTheData = BuffersStorage::getInstance().getFreeBuffer(16384);
restOfTheData->writeBytes(buffer);
restOfTheData->limit(restOfTheData->position());
lastPacketLength = 0;
if (reuseLater != nullptr) {
reuseLater->reuse();
}
break;
}
int32_t ackId = buffer->readBigInt32(nullptr) & (~(1 << 31));
ConnectionsManager::getInstance().onConnectionQuickAckReceived(this, ackId);
continue;
}
if (fByte != 0x7f) {
currentPacketLength = ((uint32_t) fByte) * 4;
} else {
buffer->position(mark);
if (buffer->remaining() < 4) {
if (restOfTheData == nullptr || (restOfTheData != nullptr && restOfTheData->position() != 0)) {
NativeByteBuffer *reuseLater = restOfTheData;
restOfTheData = BuffersStorage::getInstance().getFreeBuffer(16384);
restOfTheData->writeBytes(buffer);
restOfTheData->limit(restOfTheData->position());
lastPacketLength = 0;
if (reuseLater != nullptr) {
reuseLater->reuse();
}
} else {
restOfTheData->position(restOfTheData->limit());
}
break;
}
currentPacketLength = ((uint32_t) buffer->readInt32(nullptr) >> 8) * 4;
}
if (currentPacketLength % 4 != 0 || currentPacketLength > 2 * 1024 * 1024) {
DEBUG_E("connection(%p, dc%u, type %d) received invalid packet length", this, currentDatacenter->getDatacenterId(), connectionType);
reconnect();
return;
}
if (currentPacketLength < buffer->remaining()) {
DEBUG_E("connection(%p, dc%u, type %d) received message len %u but packet larger %u", this, currentDatacenter->getDatacenterId(), connectionType, currentPacketLength, buffer->remaining());
} else if (currentPacketLength == buffer->remaining()) {
DEBUG_E("connection(%p, dc%u, type %d) received message len %u equal to packet size", this, currentDatacenter->getDatacenterId(), connectionType, currentPacketLength);
} else {
DEBUG_E("connection(%p, dc%u, type %d) received packet size less(%u) then message size(%u)", this, currentDatacenter->getDatacenterId(), connectionType, buffer->remaining(), currentPacketLength);
NativeByteBuffer *reuseLater = nullptr;
uint32_t len = currentPacketLength + (fByte != 0x7f ? 1 : 4);
if (restOfTheData != nullptr && restOfTheData->capacity() < len) {
reuseLater = restOfTheData;
restOfTheData = nullptr;
}
if (restOfTheData == nullptr) {
buffer->position(mark);
restOfTheData = BuffersStorage::getInstance().getFreeBuffer(len);
restOfTheData->writeBytes(buffer);
} else {
restOfTheData->position(restOfTheData->limit());
restOfTheData->limit(len);
}
lastPacketLength = len;
if (reuseLater != nullptr) {
reuseLater->reuse();
}
return;
}
uint32_t old = buffer->limit();
buffer->limit(buffer->position() + currentPacketLength);
ConnectionsManager::getInstance().onConnectionDataReceived(this, buffer, currentPacketLength);
buffer->position(buffer->limit());
buffer->limit(old);
if (restOfTheData != nullptr) {
if ((lastPacketLength != 0 && restOfTheData->position() == lastPacketLength) || (lastPacketLength == 0 && !restOfTheData->hasRemaining())) {
restOfTheData->reuse();
restOfTheData = nullptr;
} else {
DEBUG_E("compact occured");
restOfTheData->compact();
restOfTheData->limit(restOfTheData->position());
restOfTheData->position(0);
}
}
if (parseLaterBuffer != nullptr) {
buffer = parseLaterBuffer;
parseLaterBuffer = nullptr;
}
}
}
void Connection::connect() {
if (!ConnectionsManager::getInstance().isNetworkAvailable()) {
ConnectionsManager::getInstance().onConnectionClosed(this);
return;
}
if ((connectionState == TcpConnectionStageConnected || connectionState == TcpConnectionStageConnecting)) {
return;
}
connectionState = TcpConnectionStageConnecting;
bool ipv6 = ConnectionsManager::getInstance().isIpv6Enabled();
if (connectionType == ConnectionTypeDownload) {
currentAddressFlags = 2;
hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags | (ipv6 ? 1 : 0));
if (hostAddress.empty()) {
currentAddressFlags = 0;
hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags | (ipv6 ? 1 : 0));
}
if (hostAddress.empty() && ipv6) {
currentAddressFlags = 2;
hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags);
if (hostAddress.empty()) {
currentAddressFlags = 0;
hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags);
}
}
} else {
currentAddressFlags = 0;
hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags | (ipv6 ? 1 : 0));
if (ipv6 && hostAddress.empty()) {
hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags);
}
}
hostPort = (uint16_t) currentDatacenter->getCurrentPort(currentAddressFlags);
reconnectTimer->stop();
DEBUG_D("connection(%p, dc%u, type %d) connecting (%s:%hu)", this, currentDatacenter->getDatacenterId(), connectionType, hostAddress.c_str(), hostPort);
firstPacketSent = false;
if (restOfTheData != nullptr) {
restOfTheData->reuse();
restOfTheData = nullptr;
}
lastPacketLength = 0;
wasConnected = false;
hasSomeDataSinceLastConnect = false;
openConnection(hostAddress, hostPort, ipv6);
if (connectionType == ConnectionTypePush) {
if (isTryingNextPort) {
setTimeout(20);
} else {
setTimeout(30);
}
} else {
if (isTryingNextPort) {
setTimeout(8);
} else {
if (connectionType == ConnectionTypeUpload) {
setTimeout(25);
} else {
setTimeout(15);
}
}
}
}
void Connection::reconnect() {
suspendConnection();
connectionState = TcpConnectionStageReconnecting;
connect();
}
void Connection::sendData(NativeByteBuffer *buff, bool reportAck) {
if (buff == nullptr) {
return;
}
buff->rewind();
if (connectionState == TcpConnectionStageIdle || connectionState == TcpConnectionStageReconnecting || connectionState == TcpConnectionStageSuspended) {
connect();
}
if (isDisconnected()) {
buff->reuse();
DEBUG_D("connection(%p, dc%u, type %d) disconnected, don't send data", this, currentDatacenter->getDatacenterId(), connectionType);
return;
}
uint32_t bufferLen = 0;
uint32_t packetLength = buff->limit() / 4;
if (packetLength < 0x7f) {
bufferLen++;
} else {
bufferLen += 4;
}
if (!firstPacketSent) {
bufferLen += 64;
}
NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(bufferLen);
uint8_t *bytes = buffer->bytes();
if (!firstPacketSent) {
buffer->position(64);
static uint8_t temp[64];
while (true) {
RAND_bytes(bytes, 64);
uint32_t val = (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | (bytes[0]);
uint32_t val2 = (bytes[7] << 24) | (bytes[6] << 16) | (bytes[5] << 8) | (bytes[4]);
if (bytes[0] != 0xef && val != 0x44414548 && val != 0x54534f50 && val != 0x20544547 && val != 0x4954504f && val != 0xeeeeeeee && val2 != 0x00000000) {
bytes[56] = bytes[57] = bytes[58] = bytes[59] = 0xef;
break;
}
}
for (int a = 0; a < 48; a++) {
temp[a] = bytes[55 - a];
}
encryptNum = decryptNum = 0;
memset(encryptCount, 0, 16);
memset(decryptCount, 0, 16);
if (AES_set_encrypt_key(bytes + 8, 256, &encryptKey) < 0) {
DEBUG_E("unable to set encryptKey");
exit(1);
}
memcpy(encryptIv, bytes + 40, 16);
if (AES_set_encrypt_key(temp, 256, &decryptKey) < 0) {
DEBUG_E("unable to set decryptKey");
exit(1);
}
memcpy(decryptIv, temp + 32, 16);
AES_ctr128_encrypt(bytes, temp, 64, &encryptKey, encryptIv, encryptCount, &encryptNum);
memcpy(bytes + 56, temp + 56, 8);
firstPacketSent = true;
}
if (packetLength < 0x7f) {
if (reportAck) {
packetLength |= (1 << 7);
}
buffer->writeByte((uint8_t) packetLength);
bytes += (buffer->limit() - 1);
AES_ctr128_encrypt(bytes, bytes, 1, &encryptKey, encryptIv, encryptCount, &encryptNum);
} else {
packetLength = (packetLength << 8) + 0x7f;
if (reportAck) {
packetLength |= (1 << 7);
}
buffer->writeInt32(packetLength);
bytes += (buffer->limit() - 4);
AES_ctr128_encrypt(bytes, bytes, 4, &encryptKey, encryptIv, encryptCount, &encryptNum);
}
buffer->rewind();
writeBuffer(buffer);
buff->rewind();
AES_ctr128_encrypt(buff->bytes(), buff->bytes(), buff->limit(), &encryptKey, encryptIv, encryptCount, &encryptNum);
writeBuffer(buff);
}
void Connection::onDisconnected(int reason) {
reconnectTimer->stop();
DEBUG_D("connection(%p, dc%u, type %d) disconnected with reason %d", this, currentDatacenter->getDatacenterId(), connectionType, reason);
bool switchToNextPort = wasConnected && !hasSomeDataSinceLastConnect && reason == 2;
firstPacketSent = false;
if (restOfTheData != nullptr) {
restOfTheData->reuse();
restOfTheData = nullptr;
}
connectionToken = 0;
lastPacketLength = 0;
wasConnected = false;
if (connectionState != TcpConnectionStageSuspended && connectionState != TcpConnectionStageIdle) {
connectionState = TcpConnectionStageIdle;
}
ConnectionsManager::getInstance().onConnectionClosed(this);
uint32_t datacenterId = currentDatacenter->getDatacenterId();
if (connectionState == TcpConnectionStageIdle && connectionType == ConnectionTypeGeneric && (currentDatacenter->isHandshaking() || datacenterId == ConnectionsManager::getInstance().currentDatacenterId || datacenterId == ConnectionsManager::getInstance().movingToDatacenterId)) {
connectionState = TcpConnectionStageReconnecting;
failedConnectionCount++;
if (failedConnectionCount == 1) {
if (hasSomeDataSinceLastConnect) {
willRetryConnectCount = 5;
} else {
willRetryConnectCount = 1;
}
}
if (ConnectionsManager::getInstance().isNetworkAvailable()) {
isTryingNextPort = true;
if (failedConnectionCount > willRetryConnectCount || switchToNextPort) {
currentDatacenter->nextAddressOrPort(currentAddressFlags);
failedConnectionCount = 0;
}
}
DEBUG_D("connection(%p, dc%u, type %d) reconnect %s:%hu", this, currentDatacenter->getDatacenterId(), connectionType, hostAddress.c_str(), hostPort);
reconnectTimer->setTimeout(1000, false);
reconnectTimer->start();
}
}
void Connection::onConnected() {
connectionState = TcpConnectionStageConnected;
connectionToken = lastConnectionToken++;
wasConnected = true;
DEBUG_D("connection(%p, dc%u, type %d) connected to %s:%hu", this, currentDatacenter->getDatacenterId(), connectionType, hostAddress.c_str(), hostPort);
ConnectionsManager::getInstance().onConnectionConnected(this);
}
Datacenter *Connection::getDatacenter() {
return currentDatacenter;
}
ConnectionType Connection::getConnectionType() {
return connectionType;
}
uint32_t Connection::getConnectionToken() {
return connectionToken;
}
-85
View File
@@ -1,85 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef CONNECTION_H
#define CONNECTION_H
#include <pthread.h>
#include <vector>
#include <string>
#include <openssl/aes.h>
#include "ConnectionSession.h"
#include "ConnectionSocket.h"
#include "Defines.h"
class Datacenter;
class Timer;
class ByteStream;
class Connection : public ConnectionSession, public ConnectionSocket {
public:
Connection(Datacenter *datacenter, ConnectionType type);
~Connection();
void connect();
void suspendConnection();
void sendData(NativeByteBuffer *buffer, bool reportAck);
uint32_t getConnectionToken();
ConnectionType getConnectionType();
Datacenter *getDatacenter();
protected:
void onReceivedData(NativeByteBuffer *buffer) override;
void onDisconnected(int reason) override;
void onConnected() override;
void reconnect();
private:
enum TcpConnectionState {
TcpConnectionStageIdle,
TcpConnectionStageConnecting,
TcpConnectionStageReconnecting,
TcpConnectionStageConnected,
TcpConnectionStageSuspended
};
TcpConnectionState connectionState = TcpConnectionStageIdle;
uint32_t connectionToken = 0;
std::string hostAddress;
uint16_t hostPort;
uint16_t failedConnectionCount;
Datacenter *currentDatacenter;
uint32_t currentAddressFlags;
ConnectionType connectionType;
bool firstPacketSent = false;
NativeByteBuffer *restOfTheData = nullptr;
uint32_t lastPacketLength = 0;
bool hasSomeDataSinceLastConnect = false;
bool isTryingNextPort = false;
bool wasConnected = false;
uint32_t willRetryConnectCount = 5;
Timer *reconnectTimer;
AES_KEY encryptKey;
uint8_t encryptIv[16];
uint32_t encryptNum;
uint8_t encryptCount[16];
AES_KEY decryptKey;
uint8_t decryptIv[16];
uint32_t decryptNum;
uint8_t decryptCount[16];
friend class ConnectionsManager;
};
#endif
@@ -1,99 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#include <algorithm>
#include <openssl/rand.h>
#include "ConnectionSession.h"
#include "MTProtoScheme.h"
#include "ConnectionsManager.h"
#include "NativeByteBuffer.h"
void ConnectionSession::recreateSession() {
processedMessageIds.clear();
messagesIdsForConfirmation.clear();
processedSessionChanges.clear();
nextSeqNo = 0;
genereateNewSessionId();
}
void ConnectionSession::genereateNewSessionId() {
int64_t newSessionId;
RAND_bytes((uint8_t *) &newSessionId, 8);
#if USE_DEBUG_SESSION
sessionId = (0xabcd000000000000L | (newSessionId & 0x0000ffffffffffffL));
#else
sessionId = newSessionId;
#endif
}
void ConnectionSession::setSessionId(int64_t id) {
sessionId = id;
}
int64_t ConnectionSession::getSissionId() {
return sessionId;
}
uint32_t ConnectionSession::generateMessageSeqNo(bool increment) {
uint32_t value = nextSeqNo;
if (increment) {
nextSeqNo++;
}
return value * 2 + (increment ? 1 : 0);
}
bool ConnectionSession::isMessageIdProcessed(int64_t messageId) {
return std::find(processedMessageIds.begin(), processedMessageIds.end(), messageId) != processedMessageIds.end();
}
void ConnectionSession::addProcessedMessageId(int64_t messageId) {
if (processedMessageIds.size() > 300) {
processedMessageIds.erase(processedMessageIds.begin(), processedMessageIds.begin() + 100);
}
processedMessageIds.push_back(messageId);
}
bool ConnectionSession::hasMessagesToConfirm() {
return !messagesIdsForConfirmation.empty();
}
void ConnectionSession::addMessageToConfirm(int64_t messageId) {
if (std::find(processedMessageIds.begin(), processedMessageIds.end(), messageId) != processedMessageIds.end()) {
return;
}
messagesIdsForConfirmation.push_back(messageId);
}
NetworkMessage *ConnectionSession::generateConfirmationRequest() {
NetworkMessage *networkMessage = nullptr;
if (!messagesIdsForConfirmation.empty()) {
TL_msgs_ack *msgAck = new TL_msgs_ack();
msgAck->msg_ids.insert(msgAck->msg_ids.begin(), messagesIdsForConfirmation.begin(), messagesIdsForConfirmation.end());
NativeByteBuffer *os = new NativeByteBuffer(true);
msgAck->serializeToStream(os);
networkMessage = new NetworkMessage();
networkMessage->message = std::unique_ptr<TL_message>(new TL_message);
networkMessage->message->msg_id = ConnectionsManager::getInstance().generateMessageId();
networkMessage->message->seqno = generateMessageSeqNo(false);
networkMessage->message->bytes = os->capacity();
networkMessage->message->body = std::unique_ptr<TLObject>(msgAck);
messagesIdsForConfirmation.clear();
}
return networkMessage;
}
bool ConnectionSession::isSessionProcessed(int64_t sessionId) {
return std::find(processedSessionChanges.begin(), processedSessionChanges.end(), sessionId) != processedSessionChanges.end();
}
void ConnectionSession::addProcessedSession(int64_t sessionId) {
processedSessionChanges.push_back(sessionId);
}
@@ -1,42 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef CONNECTIONSESSION_H
#define CONNECTIONSESSION_H
#include <stdint.h>
#include <vector>
#include "Defines.h"
class ConnectionSession {
public:
void recreateSession();
void genereateNewSessionId();
void setSessionId(int64_t id);
int64_t getSissionId();
uint32_t generateMessageSeqNo(bool increment);
bool isMessageIdProcessed(int64_t messageId);
void addProcessedMessageId(int64_t messageId);
bool hasMessagesToConfirm();
void addMessageToConfirm(int64_t messageId);
NetworkMessage *generateConfirmationRequest();
bool isSessionProcessed(int64_t sessionId);
void addProcessedSession(int64_t sessionId);
private:
int64_t sessionId;
uint32_t nextSeqNo = 0;
std::vector<int64_t> processedMessageIds;
std::vector<int64_t> messagesIdsForConfirmation;
std::vector<int64_t> processedSessionChanges;
};
#endif
@@ -1,226 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <memory.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include "ByteStream.h"
#include "ConnectionSocket.h"
#include "FileLog.h"
#include "Defines.h"
#include "ConnectionsManager.h"
#include "EventObject.h"
#include "Timer.h"
#include "NativeByteBuffer.h"
#ifndef EPOLLRDHUP
#define EPOLLRDHUP 0x2000
#endif
ConnectionSocket::ConnectionSocket() {
outgoingByteStream = new ByteStream();
lastEventTime = ConnectionsManager::getInstance().getCurrentTimeMillis();
eventObject = new EventObject(this, EventObjectTypeConnection);
}
ConnectionSocket::~ConnectionSocket() {
if (outgoingByteStream != nullptr) {
delete outgoingByteStream;
outgoingByteStream = nullptr;
}
if (eventObject != nullptr) {
delete eventObject;
eventObject = nullptr;
}
}
void ConnectionSocket::openConnection(std::string address, uint16_t port, bool ipv6) {
int epolFd = ConnectionsManager::getInstance().epolFd;
if ((socketFd = socket(ipv6 ? AF_INET6 : AF_INET, SOCK_STREAM, 0)) < 0) {
DEBUG_E("connection(%p) can't create socket", this);
closeSocket(1);
return;
}
memset(&socketAddress, 0, sizeof(sockaddr_in));
memset(&socketAddress6, 0, sizeof(sockaddr_in6));
if (ipv6) {
socketAddress6.sin6_family = AF_INET6;
socketAddress6.sin6_port = htons(port);
if (inet_pton(AF_INET6, address.c_str(), &socketAddress6.sin6_addr.s6_addr) != 1) {
DEBUG_E("connection(%p) bad ipv6 %s", this, address.c_str());
closeSocket(1);
return;
}
} else {
socketAddress.sin_family = AF_INET;
socketAddress.sin_port = htons(port);
if (inet_pton(AF_INET, address.c_str(), &socketAddress.sin_addr.s_addr) != 1) {
DEBUG_E("connection(%p) bad ipv4 %s", this, address.c_str());
closeSocket(1);
return;
}
}
int yes = 1;
if (setsockopt(socketFd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(int))) {
DEBUG_E("connection(%p) set TCP_NODELAY failed", this);
}
if (fcntl(socketFd, F_SETFL, O_NONBLOCK) == -1) {
DEBUG_E("connection(%p) set O_NONBLOCK failed", this);
closeSocket(1);
return;
}
if (connect(socketFd, (ipv6 ? (sockaddr *) &socketAddress6 : (sockaddr *) &socketAddress), (socklen_t) (ipv6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in))) == -1 && errno != EINPROGRESS) {
closeSocket(1);
} else {
eventMask.events = EPOLLOUT | EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET;
eventMask.data.ptr = eventObject;
if (epoll_ctl(epolFd, EPOLL_CTL_ADD, socketFd, &eventMask) != 0) {
DEBUG_E("connection(%p) epoll_ctl, adding socket failed", this);
closeSocket(1);
}
}
}
bool ConnectionSocket::checkSocketError() {
if (socketFd < 0) {
return true;
}
int ret;
int code;
socklen_t len = sizeof(int);
ret = getsockopt(socketFd, SOL_SOCKET, SO_ERROR, &code, &len);
return (ret || code) != 0;
}
void ConnectionSocket::closeSocket(int reason) {
lastEventTime = ConnectionsManager::getInstance().getCurrentTimeMillis();
ConnectionsManager::getInstance().detachConnection(this);
if (socketFd >= 0) {
epoll_ctl(ConnectionsManager::getInstance().epolFd, EPOLL_CTL_DEL, socketFd, NULL);
if (close(socketFd) != 0) {
DEBUG_E("connection(%p) unable to close socket", this);
}
socketFd = -1;
}
onConnectedSent = false;
outgoingByteStream->clean();
onDisconnected(reason);
}
void ConnectionSocket::onEvent(uint32_t events) {
if (events & EPOLLIN) {
if (checkSocketError()) {
closeSocket(1);
return;
} else {
ssize_t readCount;
NativeByteBuffer *buffer = ConnectionsManager::getInstance().networkBuffer;
while (true) {
buffer->rewind();
readCount = recv(socketFd, buffer->bytes(), READ_BUFFER_SIZE, 0);
if (readCount < 0) {
closeSocket(1);
DEBUG_E("connection(%p) recv failed", this);
return;
}
if (readCount > 0) {
buffer->limit((uint32_t) readCount);
lastEventTime = ConnectionsManager::getInstance().getCurrentTimeMillis();
onReceivedData(buffer);
}
if (readCount != READ_BUFFER_SIZE) {
break;
}
}
}
}
if (events & EPOLLOUT) {
if (checkSocketError() != 0) {
closeSocket(1);
return;
} else {
if (!onConnectedSent) {
ConnectionsManager::getInstance().attachConnection(this);
lastEventTime = ConnectionsManager::getInstance().getCurrentTimeMillis();
onConnected();
onConnectedSent = true;
}
NativeByteBuffer *buffer = ConnectionsManager::getInstance().networkBuffer;
buffer->clear();
outgoingByteStream->get(buffer);
buffer->flip();
uint32_t remaining = buffer->remaining();
if (remaining) {
ssize_t sentLength;
if ((sentLength = send(socketFd, buffer->bytes(), remaining, 0)) < 0) {
DEBUG_E("connection(%p) send failed", this);
closeSocket(1);
return;
} else {
outgoingByteStream->discard((uint32_t) sentLength);
adjustWriteOp();
}
}
}
}
if ((events & EPOLLRDHUP) || (events & EPOLLHUP)) {
closeSocket(1);
return;
}
if (events & EPOLLERR) {
DEBUG_E("connection(%p) epoll error", this);
return;
}
}
void ConnectionSocket::writeBuffer(NativeByteBuffer *buffer) {
outgoingByteStream->append(buffer);
adjustWriteOp();
}
void ConnectionSocket::adjustWriteOp() {
eventMask.events = EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET;
if (outgoingByteStream->hasData()) {
eventMask.events |= EPOLLOUT;
}
eventMask.data.ptr = eventObject;
if (epoll_ctl(ConnectionsManager::getInstance().epolFd, EPOLL_CTL_MOD, socketFd, &eventMask) != 0) {
DEBUG_E("connection(%p) epoll_ctl, modify socket failed", this);
closeSocket(1);
}
}
void ConnectionSocket::setTimeout(time_t time) {
timeout = time;
lastEventTime = ConnectionsManager::getInstance().getCurrentTimeMillis();
}
void ConnectionSocket::checkTimeout(int64_t now) {
if (timeout != 0 && (now - lastEventTime) > (int64_t) timeout * 1000) {
closeSocket(2);
}
}
bool ConnectionSocket::isDisconnected() {
return socketFd < 0;
}
void ConnectionSocket::dropConnection() {
closeSocket(0);
}
@@ -1,59 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef CONNECTIONSOCKET_H
#define CONNECTIONSOCKET_H
#include <sys/epoll.h>
#include <netinet/in.h>
#include <string>
class NativeByteBuffer;
class ConnectionsManager;
class ByteStream;
class EventObject;
class ConnectionSocket {
public:
ConnectionSocket();
virtual ~ConnectionSocket();
void writeBuffer(NativeByteBuffer *buffer);
void openConnection(std::string address, uint16_t port, bool ipv6);
void setTimeout(time_t timeout);
bool isDisconnected();
void dropConnection();
protected:
void onEvent(uint32_t events);
void checkTimeout(int64_t now);
virtual void onReceivedData(NativeByteBuffer *buffer) = 0;
virtual void onDisconnected(int reason) = 0;
virtual void onConnected() = 0;
private:
ByteStream *outgoingByteStream = nullptr;
struct epoll_event eventMask;
struct sockaddr_in socketAddress;
struct sockaddr_in6 socketAddress6;
int socketFd = -1;
time_t timeout = 15;
bool onConnectedSent = false;
int64_t lastEventTime = 0;
EventObject *eventObject;
bool checkSocketError();
void closeSocket(int reason);
void adjustWriteOp();
friend class EventObject;
friend class ConnectionsManager;
};
#endif
File diff suppressed because it is too large Load Diff
@@ -1,197 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef CONNECTIONSMANAGER_H
#define CONNECTIONSMANAGER_H
#include <pthread.h>
#include <queue>
#include <functional>
#include <sys/epoll.h>
#include <map>
#include <atomic>
#include <bits/unique_ptr.h>
#include "Defines.h"
#ifdef ANDROID
#include <jni.h>
#endif
class NativeByteBuffer;
class Connection;
class Datacenter;
class Request;
class DatacenterHandshake;
class TLObject;
class ConnectionSocket;
class TL_auth_exportedAuthorization;
class ByteArray;
class TL_config;
class EventObject;
class Config;
class ConnectionsManager {
public:
ConnectionsManager();
~ConnectionsManager();
static ConnectionsManager &getInstance();
int64_t getCurrentTimeMillis();
int32_t getCurrentTime();
int32_t getTimeDifference();
int32_t sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, uint32_t flags, uint32_t datacenterId, ConnectionType connetionType, bool immediate);
void sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, uint32_t flags, uint32_t datacenterId, ConnectionType connetionType, bool immediate, int32_t requestToken);
void cancelRequest(int32_t token, bool notifyServer);
void cleanUp();
void cancelRequestsForGuid(int32_t guid);
void bindRequestToGuid(int32_t requestToken, int32_t guid);
void applyDatacenterAddress(uint32_t datacenterId, std::string ipAddress, uint32_t port);
void setDelegate(ConnectiosManagerDelegate *connectiosManagerDelegate);
ConnectionState getConnectionState();
void setUserId(int32_t userId);
void switchBackend();
void resumeNetwork(bool partial);
void pauseNetwork();
void setNetworkAvailable(bool value);
void setUseIpv6(bool value);
void init(uint32_t version, int32_t layer, int32_t apiId, std::string deviceModel, std::string systemVersion, std::string appVersion, std::string langCode, std::string configPath, std::string logPath, int32_t userId, bool isPaused, bool enablePushConnection);
void updateDcSettings(uint32_t datacenterId);
void setPushConnectionEnabled(bool value);
#ifdef ANDROID
void sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, uint32_t flags, uint32_t datacenterId, ConnectionType connetionType, bool immediate, int32_t requestToken, jobject ptr1, jobject ptr2);
static void useJavaVM(JavaVM *vm, bool useJavaByteBuffers);
#endif
private:
static void *ThreadProc(void *data);
void initDatacenters();
void loadConfig();
void saveConfig();
void select();
void wakeup();
void processServerResponse(TLObject *message, int64_t messageId, int32_t messageSeqNo, int64_t messageSalt, Connection *connection, int64_t innerMsgId, int64_t containerMessageId);
void sendPing(Datacenter *datacenter, bool usePushConnection);
void sendMessagesToConnection(std::vector<std::unique_ptr<NetworkMessage>> &messages, Connection *connection, bool reportAck);
void sendMessagesToConnectionWithConfirmation(std::vector<std::unique_ptr<NetworkMessage>> &messages, Connection *connection, bool reportAck);
void requestSaltsForDatacenter(Datacenter *datacenter);
void clearRequestsForDatacenter(Datacenter *datacenter);
void registerForInternalPushUpdates();
void processRequestQueue(uint32_t connectionType, uint32_t datacenterId);
void moveToDatacenter(uint32_t datacenterId);
void authorizeOnMovingDatacenter();
void authorizedOnMovingDatacenter();
Datacenter *getDatacenterWithId(uint32_t datacenterId);
std::unique_ptr<TLObject> wrapInLayer(TLObject *object, Datacenter *datacenter, Request *baseRequest);
void removeRequestFromGuid(int32_t requestToken);
void cancelRequestInternal(int32_t token, bool notifyServer, bool removeFromClass);
int callEvents(int64_t now);
void checkPendingTasks();
void scheduleTask(std::function<void()> task);
void scheduleEvent(EventObject *eventObject, uint32_t time);
void removeEvent(EventObject *eventObject);
void onConnectionClosed(Connection *connection);
void onConnectionConnected(Connection *connection);
void onConnectionQuickAckReceived(Connection *connection, int32_t ack);
void onConnectionDataReceived(Connection *connection, NativeByteBuffer *data, uint32_t length);
void attachConnection(ConnectionSocket *connection);
void detachConnection(ConnectionSocket *connection);
TLObject *TLdeserialize(TLObject *request, uint32_t bytes, NativeByteBuffer *data);
TLObject *getRequestWithMessageId(int64_t messageId);
void onDatacenterHandshakeComplete(Datacenter *datacenter, int32_t timeDiff);
void onDatacenterExportAuthorizationComplete(Datacenter *datacenter);
int64_t generateMessageId();
bool isIpv6Enabled();
bool isNetworkAvailable();
uint32_t configVersion = 2;
Config *config = nullptr;
std::list<EventObject *> events;
std::map<uint32_t, Datacenter *> datacenters;
std::map<int32_t, std::vector<std::int32_t>> quickAckIdToRequestIds;
int32_t pingTime;
bool testBackend = false;
std::atomic<uint32_t> lastRequestToken{1};
uint32_t currentDatacenterId = 0;
uint32_t movingToDatacenterId = DEFAULT_DATACENTER_ID;
int64_t pushSessionId = 0;
int32_t currentPingTime = 0;
bool registeringForPush = false;
int64_t lastPushPingTime = 0;
bool sendingPushPing = false;
bool updatingDcSettings = false;
int32_t updatingDcStartTime = 0;
int32_t lastDcUpdateTime = 0;
int64_t lastPingTime = getCurrentTimeMillis();
bool networkPaused = false;
int32_t nextSleepTimeout = CONNECTION_BACKGROUND_KEEP_TIME;
int64_t lastPauseTime = 0;
ConnectionState connectionState = ConnectionStateConnecting;
std::unique_ptr<ByteArray> movingAuthorization;
std::vector<int64_t> sessionsToDestroy;
int32_t lastDestroySessionRequestTime;
std::map<int32_t, std::vector<int32_t>> requestsByGuids;
std::map<int32_t, int32_t> guidsByRequests;
pthread_t networkThread;
pthread_mutex_t mutex;
std::queue<std::function<void()>> pendingTasks;
struct epoll_event *epollEvents;
timespec timeSpec;
int32_t timeDifference = 0;
int64_t lastOutgoingMessageId = 0;
bool networkAvailable = true;
bool ipv6Enabled = false;
std::vector<ConnectionSocket *> activeConnections;
int epolFd;
int *pipeFd;
NativeByteBuffer *networkBuffer;
requestsList requestsQueue;
requestsList runningRequests;
std::vector<uint32_t> requestingSaltsForDc;
int32_t lastPingId = 0;
uint32_t currentVersion = 1;
int32_t currentLayer = 34;
int32_t currentApiId = 6;
std::string currentDeviceModel;
std::string currentSystemVersion;
std::string currentAppVersion;
std::string currentLangCode;
std::string currentConfigPath;
std::string currentLogPath;
int32_t currentUserId = 0;
bool registeredForInternalPush = false;
bool pushConnectionEnabled = true;
ConnectiosManagerDelegate *delegate;
friend class ConnectionSocket;
friend class ConnectionSession;
friend class Connection;
friend class Timer;
friend class Datacenter;
friend class TL_message;
friend class TL_rpc_result;
friend class Config;
};
#ifdef ANDROID
extern JavaVM *javaVm;
extern JNIEnv *jniEnv;
extern jclass jclass_ByteBuffer;
extern jmethodID jclass_ByteBuffer_allocateDirect;
#endif
#endif
File diff suppressed because it is too large Load Diff
-129
View File
@@ -1,129 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef DATACENTER_H
#define DATACENTER_H
#include <stdint.h>
#include <vector>
#include <map>
#include <bits/unique_ptr.h>
#include "Defines.h"
class TL_future_salt;
class Connection;
class NativeByteBuffer;
class TL_future_salt;
class ByteArray;
class TLObject;
class Config;
class Datacenter {
public:
Datacenter(uint32_t id);
Datacenter(NativeByteBuffer *data);
void switchTo443Port();
uint32_t getDatacenterId();
std::string getCurrentAddress(uint32_t flags);
int32_t getCurrentPort(uint32_t flags);
void addAddressAndPort(std::string address, uint32_t port, uint32_t flags);
void nextAddressOrPort(uint32_t flags);
void storeCurrentAddressAndPortNum();
void replaceAddressesAndPorts(std::vector<std::string> &newAddresses, std::map<std::string, uint32_t> &newPorts, uint32_t flags);
void serializeToStream(NativeByteBuffer *stream);
void clear();
void clearServerSalts();
int64_t getServerSalt();
void mergeServerSalts(std::vector<std::unique_ptr<TL_future_salt>> &salts);
void addServerSalt(std::unique_ptr<TL_future_salt> &serverSalt);
bool containsServerSalt(int64_t value);
void suspendConnections();
void getSessions(std::vector<int64_t> &sessions);
void recreateSessions();
bool isHandshaking();
bool hasAuthKey();
bool isExportingAuthorization();
Connection *getDownloadConnection(uint32_t num, bool create);
Connection *getUploadConnection(bool create);
Connection *getGenericConnection(bool create);
Connection *getPushConnection(bool create);
Connection *getConnectionByType(uint32_t connectionType, bool create);
private:
void onHandshakeConnectionClosed(Connection *connection);
void onHandshakeConnectionConnected(Connection *connection);
void processHandshakeResponse(TLObject *message, int64_t messageId);
void aesIgeEncryption(uint8_t *buffer, uint8_t *key, uint8_t *iv, bool encrypt, bool changeIv, uint32_t length);
NativeByteBuffer *createRequestsData(std::vector<std::unique_ptr<NetworkMessage>> &requests, int32_t *quickAckId, Connection *connection);
bool decryptServerResponse(int64_t keyId, uint8_t *key, uint8_t *data, uint32_t length);
TLObject *getCurrentHandshakeRequest();
const int32_t *defaultPorts = new int32_t[11] {-1, 80, -1, 443, -1, 443, -1, 80, -1, 443, -1};
const int32_t *defaultPorts8888 = new int32_t[11] {-1, 8888, -1, 443, -1, 8888, -1, 80, -1, 8888, -1};
uint32_t datacenterId;
Connection *genericConnection = nullptr;
Connection *downloadConnections[DOWNLOAD_CONNECTIONS_COUNT];
Connection *uploadConnection = nullptr;
Connection *pushConnection = nullptr;
uint32_t lastInitVersion = 0;
bool authorized = false;
std::vector<std::string> addressesIpv4;
std::vector<std::string> addressesIpv6;
std::vector<std::string> addressesIpv4Download;
std::vector<std::string> addressesIpv6Download;
std::map<std::string, uint32_t> ports;
std::vector<std::unique_ptr<TL_future_salt>> serverSalts;
uint32_t currentPortNumIpv4 = 0;
uint32_t currentAddressNumIpv4 = 0;
uint32_t currentPortNumIpv6 = 0;
uint32_t currentAddressNumIpv6 = 0;
uint32_t currentPortNumIpv4Download = 0;
uint32_t currentAddressNumIpv4Download = 0;
uint32_t currentPortNumIpv6Download = 0;
uint32_t currentAddressNumIpv6Download = 0;
ByteArray *authKey = nullptr;
int64_t authKeyId = 0;
int32_t overridePort = -1;
Config *config = nullptr;
const uint32_t configVersion = 5;
const uint32_t paramsConfigVersion = 1;
Connection *createDownloadConnection(uint32_t num);
Connection *createUploadConnection();
Connection *createGenericConnection();
Connection *createPushConnection();
Connection *createConnectionByType(uint32_t connectionType);
uint8_t handshakeState = 0;
TLObject *handshakeRequest = nullptr;
ByteArray *authNonce = nullptr;
ByteArray *authServerNonce = nullptr;
ByteArray *authNewNonce = nullptr;
ByteArray *handshakeAuthKey = nullptr;
TL_future_salt *handshakeServerSalt = nullptr;
int32_t timeDifference = 0;
bool needResendData = false;
void beginHandshake(bool reconnect);
void sendRequestData(TLObject *object, bool important);
void cleanupHandshake();
void sendAckRequest(int64_t messageId);
int32_t selectPublicKey(std::vector<int64_t> &fingerprints);
bool exportingAuthorization = false;
void exportAuthorization();
friend class ConnectionsManager;
};
#endif
-99
View File
@@ -1,99 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef DEFINES_H
#define DEFINES_H
#include <functional>
#include <list>
#include <limits.h>
#include <bits/unique_ptr.h>
#include <sstream>
#define USE_DEBUG_SESSION false
#define READ_BUFFER_SIZE 1024 * 128
//#define DEBUG_VERSION
#define DEFAULT_DATACENTER_ID INT_MAX
#define DC_UPDATE_TIME 60 * 60
#define DOWNLOAD_CONNECTIONS_COUNT 2
#define CONNECTION_BACKGROUND_KEEP_TIME 10000
class TLObject;
class TL_error;
class Request;
class TL_message;
class TL_config;
class NativeByteBuffer;
typedef std::function<void(TLObject *response, TL_error *error)> onCompleteFunc;
typedef std::function<void()> onQuickAckFunc;
typedef std::list<std::unique_ptr<Request>> requestsList;
typedef requestsList::iterator requestsIter;
typedef struct NetworkMessage {
std::unique_ptr<TL_message> message;
bool invokeAfter = false;
bool needQuickAck = false;
int32_t requestId;
} NetworkMessage;
enum ConnectionType {
ConnectionTypeGeneric = 1,
ConnectionTypeDownload = 2,
ConnectionTypeUpload = 4,
ConnectionTypePush = 8,
};
enum ConnectionState {
ConnectionStateConnecting = 1,
ConnectionStateWaitingForNetwork = 2,
ConnectionStateConnected = 3
};
enum EventObjectType {
EventObjectTypeConnection,
EventObjectTypeTimer,
EventObjectPipe
};
typedef struct ConnectiosManagerDelegate {
virtual void onUpdate() = 0;
virtual void onSessionCreated() = 0;
virtual void onConnectionStateChanged(ConnectionState state) = 0;
virtual void onUnparsedMessageReceived(int64_t reqMessageId, NativeByteBuffer *buffer, ConnectionType connectionType) = 0;
virtual void onLogout() = 0;
virtual void onUpdateConfig(TL_config *config) = 0;
virtual void onInternalPushReceived() = 0;
} ConnectiosManagerDelegate;
#define AllConnectionTypes ConnectionTypeGeneric | ConnectionTypeDownload | ConnectionTypeUpload
enum RequestFlag {
RequestFlagEnableUnauthorized = 1,
RequestFlagFailOnServerErrors = 2,
RequestFlagCanCompress = 4,
RequestFlagWithoutLogin = 8,
RequestFlagTryDifferentDc = 16,
RequestFlagForceDownload = 32,
RequestFlagInvokeAfter = 64,
RequestFlagNeedQuickAck = 128
};
inline std::string to_string_int32(int32_t value) {
char buf[30];
int len = sprintf(buf, "%d", value);
return std::string(buf, len);
}
inline std::string to_string_uint64(uint64_t value) {
char buf[30];
int len = sprintf(buf, "%llu", value);
return std::string(buf, len);
}
#endif
-43
View File
@@ -1,43 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#include <unistd.h>
#include "EventObject.h"
#include "Connection.h"
#include "Timer.h"
EventObject::EventObject(void *object, EventObjectType type) {
eventObject = object;
eventType = type;
}
void EventObject::onEvent(uint32_t events) {
switch (eventType) {
case EventObjectTypeConnection: {
Connection *connection = (Connection *) eventObject;
connection->onEvent(events);
break;
}
case EventObjectTypeTimer: {
Timer *timer = (Timer *) eventObject;
timer->onEvent();
break;
}
case EventObjectPipe: {
int *pipe = (int *) eventObject;
char ch;
ssize_t size = 1;
while (size > 0) {
size = read(pipe[0], &ch, 1);
}
break;
}
default:
break;
}
}
-26
View File
@@ -1,26 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef EVENTOBJECT_H
#define EVENTOBJECT_H
#include <stdint.h>
#include "Defines.h"
class EventObject {
public:
EventObject(void *object, EventObjectType type);
void onEvent(uint32_t events);
int64_t time;
void *eventObject;
EventObjectType eventType;
};
#endif
-93
View File
@@ -1,93 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include "FileLog.h"
#ifdef ANDROID
#include <android/log.h>
#endif
FILE *logFile = nullptr;
void FileLog::init(std::string path) {
if (path.size() > 0) {
logFile = fopen(path.c_str(), "w");
}
}
void FileLog::e(const char *message, ...) {
va_list argptr;
va_start(argptr, message);
time_t t = time(0);
struct tm *now = localtime(&t);
#ifdef ANDROID
__android_log_vprint(ANDROID_LOG_ERROR, "tgnet", message, argptr);
#else
printf("%d-%d %02d:%02d:%02d error: ", now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
vprintf(message, argptr);
printf("\n");
fflush(stdout);
#endif
if (logFile) {
fprintf(logFile, "%d-%d %02d:%02d:%02d error: ", now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
vfprintf(logFile, message, argptr);
fprintf(logFile, "\n");
fflush(logFile);
}
va_end(argptr);
}
void FileLog::w(const char *message, ...) {
va_list argptr;
va_start(argptr, message);
time_t t = time(0);
struct tm *now = localtime(&t);
#ifdef ANDROID
__android_log_vprint(ANDROID_LOG_WARN, "tgnet", message, argptr);
#else
printf("%d-%d %02d:%02d:%02d warning: ", now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
vprintf(message, argptr);
printf("\n");
fflush(stdout);
#endif
if (logFile) {
fprintf(logFile, "%d-%d %02d:%02d:%02d warning: ", now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
vfprintf(logFile, message, argptr);
fprintf(logFile, "\n");
fflush(logFile);
}
va_end(argptr);
}
void FileLog::d(const char *message, ...) {
va_list argptr;
va_start(argptr, message);
time_t t = time(0);
struct tm *now = localtime(&t);
#ifdef ANDROID
__android_log_vprint(ANDROID_LOG_DEBUG, "tgnet", message, argptr);
#else
printf("%d-%d %02d:%02d:%02d debug: ", now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
vprintf(message, argptr);
printf("\n");
fflush(stdout);
#endif
if (logFile) {
fprintf(logFile, "%d-%d %02d:%02d:%02d debug: ", now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
vfprintf(logFile, message, argptr);
fprintf(logFile, "\n");
fflush(logFile);
}
va_end(argptr);
}
-32
View File
@@ -1,32 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef FILELOG_H
#define FILELOG_H
#include "Defines.h"
class FileLog {
public:
static void init(std::string path);
static void e(const char *message, ...) __attribute__((format (printf, 1, 2)));
static void w(const char *message, ...) __attribute__((format (printf, 1, 2)));
static void d(const char *message, ...) __attribute__((format (printf, 1, 2)));
};
#ifdef DEBUG_VERSION
#define DEBUG_E FileLog::e
#define DEBUG_W FileLog::w
#define DEBUG_D FileLog::d
#else
#define DEBUG_E
#define DEBUG_W
#define DEBUG_D
#endif
#endif
File diff suppressed because it is too large Load Diff
-990
View File
@@ -1,990 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef MTPROTOSCHEME_H
#define MTPROTOSCHEME_H
#include <vector>
#include <memory>
#include <map>
#include <bits/unique_ptr.h>
#include "TLObject.h"
class ByteArray;
class NativeByteBuffer;
class TLClassStore {
public:
static TLObject *TLdeserialize(NativeByteBuffer *stream, uint32_t bytes, uint32_t constructor, bool &error);
};
class TL_api_request : public TLObject {
public:
NativeByteBuffer *request = nullptr;
~TL_api_request();
bool isNeedLayer();
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t bytes, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_api_response : public TLObject {
public:
std::unique_ptr<NativeByteBuffer> response;
void readParamsEx(NativeByteBuffer *stream, uint32_t bytes, bool &error);
};
class TL_future_salt : public TLObject {
public:
static const uint32_t constructor = 0x0949d9dc;
int32_t valid_since;
int32_t valid_until;
int64_t salt;
static TL_future_salt *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_msgs_state_info : public TLObject {
public:
static const uint32_t constructor = 0x04deb57d;
int64_t req_msg_id;
std::unique_ptr<ByteArray> info;
static TL_msgs_state_info *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class Server_DH_Params : public TLObject {
public:
std::unique_ptr<ByteArray> nonce;
std::unique_ptr<ByteArray> server_nonce;
std::unique_ptr<ByteArray> new_nonce_hash;
std::unique_ptr<ByteArray> encrypted_answer;
static Server_DH_Params *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
};
class TL_server_DH_params_fail : public Server_DH_Params {
public:
static const uint32_t constructor = 0x79cb045d;
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_server_DH_params_ok : public Server_DH_Params {
public:
static const uint32_t constructor = 0xd0e8075c;
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_resPQ : public TLObject {
public:
static const uint32_t constructor = 0x05162463;
std::unique_ptr<ByteArray> nonce;
std::unique_ptr<ByteArray> server_nonce;
std::unique_ptr<ByteArray> pq;
std::vector<int64_t> server_public_key_fingerprints;
static TL_resPQ *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_p_q_inner_data : public TLObject {
public:
static const uint32_t constructor = 0x83c95aec;
std::unique_ptr<ByteArray> pq;
std::unique_ptr<ByteArray> p;
std::unique_ptr<ByteArray> q;
std::unique_ptr<ByteArray> nonce;
std::unique_ptr<ByteArray> server_nonce;
std::unique_ptr<ByteArray> new_nonce;
void serializeToStream(NativeByteBuffer *stream);
};
class TL_pong : public TLObject {
public:
static const uint32_t constructor = 0x347773c5;
int64_t msg_id;
int64_t ping_id;
static TL_pong *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_future_salts : public TLObject {
public:
static const uint32_t constructor = 0xae500895;
int64_t req_msg_id;
int32_t now;
std::vector<std::unique_ptr<TL_future_salt>> salts;
static TL_future_salts *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
};
class RpcDropAnswer : public TLObject {
public:
int64_t msg_id;
int32_t seq_no;
int32_t bytes;
static RpcDropAnswer *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
};
class TL_rpc_answer_unknown : public RpcDropAnswer {
public:
static const uint32_t constructor = 0x5e2ad36e;
void serializeToStream(NativeByteBuffer *stream);
};
class TL_rpc_answer_dropped : public RpcDropAnswer {
public:
static const uint32_t constructor = 0xa43ad8b7;
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_rpc_answer_dropped_running : public RpcDropAnswer {
public:
static const uint32_t constructor = 0xcd78e586;
void serializeToStream(NativeByteBuffer *stream);
};
class Set_client_DH_params_answer : public TLObject {
public:
std::unique_ptr<ByteArray> nonce;
std::unique_ptr<ByteArray> server_nonce;
std::unique_ptr<ByteArray> new_nonce_hash2;
std::unique_ptr<ByteArray> new_nonce_hash3;
std::unique_ptr<ByteArray> new_nonce_hash1;
static Set_client_DH_params_answer *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
};
class TL_message : public TLObject {
public:
static const uint32_t constructor = 0x5bb8e511;
int64_t msg_id;
int32_t seqno;
int32_t bytes;
std::unique_ptr<TLObject> body;
TLObject *outgoingBody = nullptr;
std::unique_ptr<NativeByteBuffer> unparsedBody;
static TL_message *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_dh_gen_retry : public Set_client_DH_params_answer {
public:
static const uint32_t constructor = 0x46dc1fb9;
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_dh_gen_fail : public Set_client_DH_params_answer {
public:
static const uint32_t constructor = 0xa69dae02;
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_dh_gen_ok : public Set_client_DH_params_answer {
public:
static const uint32_t constructor = 0x3bcbf734;
void readParams(NativeByteBuffer *stream, bool &error);
};
class BadMsgNotification : public TLObject {
public:
int64_t bad_msg_id;
int32_t bad_msg_seqno;
int32_t error_code;
int64_t new_server_salt;
static BadMsgNotification *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
};
class TL_bad_msg_notification : public BadMsgNotification {
public:
static const uint32_t constructor = 0xa7eff811;
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_bad_server_salt : public BadMsgNotification {
public:
static const uint32_t constructor = 0xedab447b;
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_msgs_state_req : public TLObject {
public:
static const uint32_t constructor = 0xda69fb52;
std::vector<int64_t> msg_ids;
static TL_msgs_state_req *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class MsgDetailedInfo : public TLObject {
public:
int64_t answer_msg_id;
int32_t bytes;
int32_t status;
int64_t msg_id;
static MsgDetailedInfo *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
};
class TL_msg_new_detailed_info : public MsgDetailedInfo {
public:
static const uint32_t constructor = 0x809db6df;
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_msg_detailed_info : public MsgDetailedInfo {
public:
static const uint32_t constructor = 0x276d3ec6;
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_msg_copy : public TLObject {
public:
static const uint32_t constructor = 0xe06046b2;
std::unique_ptr<TL_message> orig_message;
static TL_msg_copy *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_msgs_all_info : public TLObject {
public:
static const uint32_t constructor = 0x8cc0d131;
std::vector<int64_t> msg_ids;
std::unique_ptr<ByteArray> info;
static TL_msgs_all_info *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_rpc_result : public TLObject {
public:
static const uint32_t constructor = 0xf35c6d01;
int64_t req_msg_id;
std::unique_ptr<TLObject> result;
void readParamsEx(NativeByteBuffer *stream, uint32_t bytes, bool &error);
};
class TL_new_session_created : public TLObject {
public:
static const uint32_t constructor = 0x9ec20908;
int64_t first_msg_id;
int64_t unique_id;
int64_t server_salt;
void readParams(NativeByteBuffer *stream, bool &error);
};
class DestroySessionRes : public TLObject {
public:
int64_t session_id;
static DestroySessionRes *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
};
class TL_destroy_session_ok : public DestroySessionRes {
public:
static const uint32_t constructor = 0xe22045fc;
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_destroy_session_none : public DestroySessionRes {
public:
static const uint32_t constructor = 0x62d350c9;
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_msgs_ack : public TLObject {
public:
static const uint32_t constructor = 0x62d6b459;
std::vector<int64_t> msg_ids;
static TL_msgs_ack *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_msg_container : public TLObject {
public:
static const uint32_t constructor = 0x73f1f8dc;
std::vector<std::unique_ptr<TL_message>> messages;
static TL_msg_container *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_msg_resend_req : public TLObject {
public:
static const uint32_t constructor = 0x7d861a08;
std::vector<int64_t> msg_ids;
static TL_msg_resend_req *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class RpcError : public TLObject {
public:
int32_t error_code;
std::string error_message;
int64_t query_id;
};
class TL_rpc_error : public RpcError {
public:
static const uint32_t constructor = 0x2144ca19;
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_rpc_req_error : public RpcError {
public:
static const uint32_t constructor = 0x7ae432f5;
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_client_DH_inner_data : public TLObject {
public:
static const uint32_t constructor = 0x6643b654;
std::unique_ptr<ByteArray> nonce;
std::unique_ptr<ByteArray> server_nonce;
int64_t retry_id;
std::unique_ptr<ByteArray> g_b;
void serializeToStream(NativeByteBuffer *stream);
};
class TL_server_DH_inner_data : public TLObject {
public:
static const uint32_t constructor = 0xb5890dba;
std::unique_ptr<ByteArray> nonce;
std::unique_ptr<ByteArray> server_nonce;
uint32_t g;
std::unique_ptr<ByteArray> dh_prime;
std::unique_ptr<ByteArray> g_a;
int32_t server_time;
static TL_server_DH_inner_data *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_req_pq : public TLObject {
public:
static const uint32_t constructor = 0x60469778;
std::unique_ptr<ByteArray> nonce;
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_req_DH_params : public TLObject {
public:
static const uint32_t constructor = 0xd712e4be;
std::unique_ptr<ByteArray> nonce;
std::unique_ptr<ByteArray> server_nonce;
std::unique_ptr<ByteArray> p;
std::unique_ptr<ByteArray> q;
int64_t public_key_fingerprint;
std::unique_ptr<ByteArray> encrypted_data;
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_set_client_DH_params : public TLObject {
public:
static const uint32_t constructor = 0xf5045f1f;
std::unique_ptr<ByteArray> nonce;
std::unique_ptr<ByteArray> server_nonce;
std::unique_ptr<ByteArray> encrypted_data;
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_rpc_drop_answer : public TLObject {
public:
static const uint32_t constructor = 0x58e4a740;
int64_t req_msg_id;
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_get_future_salts : public TLObject {
public:
static const uint32_t constructor = 0xb921bd04;
int32_t num;
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_ping : public TLObject {
public:
static const uint32_t constructor = 0x7abe77ec;
int64_t ping_id;
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_ping_delay_disconnect : public TLObject {
public:
static const uint32_t constructor = 0xf3427b8c;
int64_t ping_id;
int32_t disconnect_delay;
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_destroy_session : public TLObject {
public:
static const uint32_t constructor = 0xe7512126;
int64_t session_id;
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_gzip_packed : public TLObject {
public:
static const uint32_t constructor = 0x3072cfa1;
NativeByteBuffer *packed_data_to_send = nullptr;
std::unique_ptr<NativeByteBuffer> packed_data;
std::unique_ptr<TLObject> originalRequest;
~TL_gzip_packed();
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_error : public TLObject {
public:
static const uint32_t constructor = 0xc4b9f9bb;
int32_t code;
std::string text;
static TL_error *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_invokeAfterMsg : public TLObject {
public:
static const uint32_t constructor = 0xcb9f372d;
int64_t msg_id;
TLObject *outgoingQuery = nullptr;
std::unique_ptr<TLObject> query;
void serializeToStream(NativeByteBuffer *stream);
};
class invokeWithLayer : public TLObject {
public:
static const uint32_t constructor = 0xda9b0d0d;
int32_t layer;
std::unique_ptr<TLObject> query;
void serializeToStream(NativeByteBuffer *stream);
};
class initConnection : public TLObject {
public:
static const uint32_t constructor = 0x69796de9;
int32_t api_id;
std::string device_model;
std::string system_version;
std::string app_version;
std::string lang_code;
std::unique_ptr<TLObject> query;
void serializeToStream(NativeByteBuffer *stream);
};
class TL_dcOption : public TLObject {
public:
static const uint32_t constructor = 0x5d8c6cc;
int32_t flags;
int32_t id;
std::string ip_address;
int32_t port;
static TL_dcOption *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_disabledFeature : public TLObject {
public:
static const uint32_t constructor = 0xae636f24;
std::string feature;
std::string description;
static TL_disabledFeature *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_config : public TLObject {
public:
static const uint32_t constructor = 0xc9411388;
int32_t date;
int32_t expires;
bool test_mode;
int32_t this_dc;
std::vector<std::unique_ptr<TL_dcOption>> dc_options;
int32_t chat_size_max;
int32_t megagroup_size_max;
int32_t forwarded_count_max;
int32_t online_update_period_ms;
int32_t offline_blur_timeout_ms;
int32_t offline_idle_timeout_ms;
int32_t online_cloud_timeout_ms;
int32_t notify_cloud_delay_ms;
int32_t notify_default_delay_ms;
int32_t chat_big_size;
int32_t push_chat_period_ms;
int32_t push_chat_limit;
int32_t saved_gifs_limit;
int32_t edit_time_limit;
int32_t rating_e_decay;
std::vector<std::unique_ptr<TL_disabledFeature>> disabled_features;
static TL_config *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_help_getConfig : public TLObject {
public:
static const uint32_t constructor = 0xc4f9186b;
bool isNeedLayer();
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class Bool : public TLObject {
public:
static Bool *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
};
class TL_boolTrue : public Bool {
public:
static const uint32_t constructor = 0x997275b5;
void serializeToStream(NativeByteBuffer *stream);
};
class TL_boolFalse : public Bool {
public:
static const uint32_t constructor = 0xbc799737;
void serializeToStream(NativeByteBuffer *stream);
};
class TL_account_registerDevice : public TLObject {
public:
static const uint32_t constructor = 0x446c712c;
int32_t token_type;
std::string token;
std::string device_model;
std::string system_version;
std::string app_version;
bool app_sandbox;
std::string lang_code;
bool isNeedLayer();
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class UserStatus : public TLObject {
public:
int32_t expires;
static UserStatus *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
};
class TL_userStatusOffline : public UserStatus {
public:
static const uint32_t constructor = 0x8c703f;
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_userStatusLastWeek : public UserStatus {
public:
static const uint32_t constructor = 0x7bf09fc;
void serializeToStream(NativeByteBuffer *stream);
};
class TL_userStatusEmpty : public UserStatus {
public:
static const uint32_t constructor = 0x9d05049;
void serializeToStream(NativeByteBuffer *stream);
};
class TL_userStatusLastMonth : public UserStatus {
public:
static const uint32_t constructor = 0x77ebc742;
void serializeToStream(NativeByteBuffer *stream);
};
class TL_userStatusOnline : public UserStatus {
public:
static const uint32_t constructor = 0xedb93949;
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_userStatusRecently : public UserStatus {
public:
static const uint32_t constructor = 0xe26f42f1;
void serializeToStream(NativeByteBuffer *stream);
};
class FileLocation : public TLObject {
public:
int32_t dc_id;
int64_t volume_id;
int32_t local_id;
int64_t secret;
static FileLocation *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
};
class TL_fileLocation : public FileLocation {
public:
static const uint32_t constructor = 0x53d69076;
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_fileLocationUnavailable : public FileLocation {
public:
static const uint32_t constructor = 0x7c596b46;
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class UserProfilePhoto : public TLObject {
public:
int64_t photo_id;
std::unique_ptr<FileLocation> photo_small;
std::unique_ptr<FileLocation> photo_big;
static UserProfilePhoto *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
};
class TL_userProfilePhotoEmpty : public UserProfilePhoto {
public:
static const uint32_t constructor = 0x4f11bae1;
void serializeToStream(NativeByteBuffer *stream);
};
class TL_userProfilePhoto : public UserProfilePhoto {
public:
static const uint32_t constructor = 0xd559d8c8;
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class User : public TLObject {
public:
int32_t id;
std::string first_name;
std::string last_name;
std::string username;
int64_t access_hash;
std::string phone;
std::unique_ptr<UserProfilePhoto> photo;
std::unique_ptr<UserStatus> status;
int32_t flags;
int32_t bot_info_version;
std::string restriction_reason;
std::string bot_inline_placeholder;
static User *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
};
class TL_userEmpty : public User {
public:
static const uint32_t constructor = 0x200250ba;
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_user : public User {
public:
static const uint32_t constructor = 0xd10d979a;
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_auth_authorization : public TLObject {
public:
static const uint32_t constructor = 0xff036af1;
std::unique_ptr<User> user;
static TL_auth_authorization *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_auth_exportedAuthorization : public TLObject {
public:
static const uint32_t constructor = 0xdf969c2d;
int32_t id;
std::unique_ptr<ByteArray> bytes;
static TL_auth_exportedAuthorization *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void readParams(NativeByteBuffer *stream, bool &error);
};
class TL_auth_exportAuthorization : public TLObject {
public:
static const uint32_t constructor = 0xe5bfffcd;
int32_t dc_id;
bool isNeedLayer();
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_auth_importAuthorization : public TLObject {
public:
static const uint32_t constructor = 0xe3ef9613;
int32_t id;
std::unique_ptr<ByteArray> bytes;
bool isNeedLayer();
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class auth_SentCode : public TLObject {
public:
bool phone_registered;
std::string phone_code_hash;
int32_t send_call_timeout;
bool is_password;
static auth_SentCode *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);
};
class TL_auth_sentAppCode : public auth_SentCode {
public:
static const uint32_t constructor = 0xe325edcf;
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_auth_sentCode : public auth_SentCode {
public:
static const uint32_t constructor = 0xefed51d9;
void readParams(NativeByteBuffer *stream, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_auth_sendCode : public TLObject {
public:
static const uint32_t constructor = 0x768d5f4d;
std::string phone_number;
int32_t sms_type;
int32_t api_id;
std::string api_hash;
std::string lang_code;
TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
void serializeToStream(NativeByteBuffer *stream);
};
class TL_updatesTooLong : public TLObject {
public:
static const uint32_t constructor = 0xe317af7e;
void serializeToStream(NativeByteBuffer *stream);
};
#endif
@@ -1,703 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#include <memory.h>
#include <stdlib.h>
#include "NativeByteBuffer.h"
#include "FileLog.h"
#include "ByteArray.h"
#include "ConnectionsManager.h"
#include "BuffersStorage.h"
NativeByteBuffer::NativeByteBuffer(uint32_t size) {
#ifdef ANDROID
if (jclass_ByteBuffer != nullptr) {
JNIEnv *env = 0;
if (javaVm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
DEBUG_E("can't get jnienv");
exit(1);
}
javaByteBuffer = env->CallStaticObjectMethod(jclass_ByteBuffer, jclass_ByteBuffer_allocateDirect, size);
if (javaByteBuffer == nullptr) {
DEBUG_E("can't create javaByteBuffer");
exit(1);
}
jobject globalRef = env->NewGlobalRef(javaByteBuffer);
env->DeleteLocalRef(javaByteBuffer);
javaByteBuffer = globalRef;
buffer = (uint8_t *) env->GetDirectBufferAddress(javaByteBuffer);
bufferOwner = false;
} else {
#endif
buffer = new uint8_t[size];
bufferOwner = true;
#ifdef ANDROID
}
#endif
if (buffer == nullptr) {
DEBUG_E("can't allocate NativeByteBuffer buffer");
exit(1);
}
_limit = _capacity = size;
}
NativeByteBuffer::NativeByteBuffer(bool calculate) {
calculateSizeOnly = calculate;
}
NativeByteBuffer::NativeByteBuffer(uint8_t *buff, uint32_t length) {
buffer = buff;
sliced = true;
_limit = _capacity = length;
}
NativeByteBuffer::~NativeByteBuffer() {
#ifdef ANDROID
if (javaByteBuffer != nullptr) {
JNIEnv *env = 0;
if (javaVm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
DEBUG_E("can't get jnienv");
exit(1);
}
env->DeleteGlobalRef(javaByteBuffer);
javaByteBuffer = nullptr;
}
#endif
if (bufferOwner && !sliced && buffer != nullptr) {
delete[] buffer;
buffer = nullptr;
}
}
uint32_t NativeByteBuffer::position() {
return _position;
}
void NativeByteBuffer::position(uint32_t position) {
if (position > _limit) {
return;
}
_position = position;
}
uint32_t NativeByteBuffer::capacity() {
return _capacity;
}
uint32_t NativeByteBuffer::limit() {
return _limit;
}
uint32_t NativeByteBuffer::remaining() {
return _limit - _position;
}
void NativeByteBuffer::clearCapacity() {
if (!calculateSizeOnly) {
return;
}
_capacity = 0;
}
void NativeByteBuffer::limit(uint32_t limit) {
if (limit > _capacity) {
return;
}
if (_position > limit) {
_position = limit;
}
_limit = limit;
}
void NativeByteBuffer::flip() {
_limit = _position;
_position = 0;
}
void NativeByteBuffer::clear() {
_position = 0;
_limit = _capacity;
}
uint8_t *NativeByteBuffer::bytes() {
return buffer;
}
void NativeByteBuffer::rewind() {
_position = 0;
}
void NativeByteBuffer::compact() {
if (_position == _limit) {
return;
}
memmove(buffer, buffer + _position, sizeof(uint8_t) * (_limit - _position));
_position = (_limit - _position);
_limit = _capacity;
}
bool NativeByteBuffer::hasRemaining() {
return _position < _limit;
}
void NativeByteBuffer::skip(uint32_t length) {
if (!calculateSizeOnly) {
if (_position + length > _limit) {
return;
}
_position += length;
} else {
_capacity += length;
}
}
void NativeByteBuffer::writeInt32(int32_t x, bool *error) {
if (!calculateSizeOnly) {
if (_position + 4 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("write int32 error");
return;
}
buffer[_position++] = (uint8_t) x;
buffer[_position++] = (uint8_t) (x >> 8);
buffer[_position++] = (uint8_t) (x >> 16);
buffer[_position++] = (uint8_t) (x >> 24);
} else {
_capacity += 4;
}
}
void NativeByteBuffer::writeInt64(int64_t x, bool *error) {
if (!calculateSizeOnly) {
if (_position + 8 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("write int64 error");
return;
}
buffer[_position++] = (uint8_t) x;
buffer[_position++] = (uint8_t) (x >> 8);
buffer[_position++] = (uint8_t) (x >> 16);
buffer[_position++] = (uint8_t) (x >> 24);
buffer[_position++] = (uint8_t) (x >> 32);
buffer[_position++] = (uint8_t) (x >> 40);
buffer[_position++] = (uint8_t) (x >> 48);
buffer[_position++] = (uint8_t) (x >> 56);
} else {
_capacity += 8;
}
}
void NativeByteBuffer::writeBool(bool value, bool *error) {
if (!calculateSizeOnly) {
if (value) {
writeInt32(0x997275b5, error);
} else {
writeInt32(0xbc799737, error);
}
} else {
_capacity += 4;
}
}
void NativeByteBuffer::writeBytes(uint8_t *b, uint32_t length, bool *error) {
if (!calculateSizeOnly) {
if (_position + length > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("write bytes error");
return;
}
writeBytesInternal(b, 0, length);
} else {
_capacity += length;
}
}
void NativeByteBuffer::writeBytes(uint8_t *b, uint32_t offset, uint32_t length, bool *error) {
if (!calculateSizeOnly) {
if (_position + length > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("write bytes error");
return;
}
writeBytesInternal(b, offset, length);
} else {
_capacity += length;
}
}
void NativeByteBuffer::writeBytes(NativeByteBuffer *b, bool *error) {
uint32_t length = b->_limit - b->_position;
if (length == 0) {
return;
}
if (!calculateSizeOnly) {
if (_position + length > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("write bytes error");
return;
}
writeBytesInternal(b->buffer + b->_position, 0, length);
b->position(b->limit());
} else {
_capacity += length;
}
}
void NativeByteBuffer::writeBytes(ByteArray *b, bool *error) {
if (!calculateSizeOnly) {
if (_position + b->length > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("write bytes error");
return;
}
writeBytesInternal(b->bytes, 0, b->length);
} else {
_capacity += b->length;
}
}
void NativeByteBuffer::writeBytesInternal(uint8_t *b, uint32_t offset, uint32_t length) {
memcpy(buffer + _position, b + offset, sizeof(uint8_t) * length);
_position += length;
}
void NativeByteBuffer::writeByte(uint8_t i, bool *error) {
if (!calculateSizeOnly) {
if (_position + 1 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("write byte error");
return;
}
buffer[_position++] = i;
} else {
_capacity += 1;
}
}
void NativeByteBuffer::writeString(std::string s, bool *error) {
writeByteArray((uint8_t *) s.c_str(), (uint32_t) s.length(), error);
}
void NativeByteBuffer::writeByteArray(uint8_t *b, uint32_t offset, uint32_t length, bool *error) {
if (length <= 253) {
if (!calculateSizeOnly) {
if (_position + 1 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("write byte array error");
return;
}
buffer[_position++] = (uint8_t) length;
} else {
_capacity += 1;
}
} else {
if (!calculateSizeOnly) {
if (_position + 4 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("write byte array error");
return;
}
buffer[_position++] = (uint8_t) 254;
buffer[_position++] = (uint8_t) length;
buffer[_position++] = (uint8_t) (length >> 8);
buffer[_position++] = (uint8_t) (length >> 16);
} else {
_capacity += 4;
}
}
if (!calculateSizeOnly) {
if (_position + length > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("write byte array error");
return;
}
writeBytesInternal(b, offset, length);
} else {
_capacity += length;
}
uint32_t addition = (length + (length <= 253 ? 1 : 4)) % 4;
if (addition != 0) {
addition = 4 - addition;
}
if (!calculateSizeOnly && _position + addition > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("write byte array error");
return;
}
for (uint32_t a = 0; a < addition; a++) {
if (!calculateSizeOnly) {
buffer[_position++] = (uint8_t) 0;
} else {
_capacity += 1;
}
}
}
void NativeByteBuffer::writeByteArray(uint8_t *b, uint32_t length, bool *error) {
writeByteArray(b, 0, length, error);
}
void NativeByteBuffer::writeByteArray(NativeByteBuffer *b, bool *error) {
b->rewind();
writeByteArray(b->buffer, 0, b->limit(), error);
}
void NativeByteBuffer::writeByteArray(ByteArray *b, bool *error) {
writeByteArray(b->bytes, 0, b->length, error);
}
void NativeByteBuffer::writeDouble(double d, bool *error) {
int64_t value;
memcpy(&value, &d, sizeof(int64_t));
writeInt64(value, error);
}
void NativeByteBuffer::writeInt32(int32_t x) {
writeInt32(x, nullptr);
}
void NativeByteBuffer::writeInt64(int64_t x) {
writeInt64(x, nullptr);
}
void NativeByteBuffer::writeBool(bool value) {
writeBool(value, nullptr);
}
void NativeByteBuffer::writeBytes(uint8_t *b, uint32_t length) {
writeBytes(b, length, nullptr);
}
void NativeByteBuffer::writeBytes(uint8_t *b, uint32_t offset, uint32_t length) {
writeBytes(b, offset, length, nullptr);
}
void NativeByteBuffer::writeBytes(ByteArray *b) {
writeBytes(b, nullptr);
}
void NativeByteBuffer::writeBytes(NativeByteBuffer *b) {
writeBytes(b, nullptr);
}
void NativeByteBuffer::writeByte(uint8_t i) {
writeByte(i, nullptr);
}
void NativeByteBuffer::writeString(std::string s) {
writeString(s, nullptr);
}
void NativeByteBuffer::writeByteArray(uint8_t *b, uint32_t offset, uint32_t length) {
writeByteArray(b, offset, length, nullptr);
}
void NativeByteBuffer::writeByteArray(uint8_t *b, uint32_t length) {
writeByteArray(b, length, nullptr);
}
void NativeByteBuffer::writeByteArray(NativeByteBuffer *b) {
writeByteArray(b, nullptr);
}
void NativeByteBuffer::writeByteArray(ByteArray *b) {
writeByteArray(b->bytes, b->length, nullptr);
}
void NativeByteBuffer::writeDouble(double d) {
writeDouble(d, nullptr);
}
int32_t NativeByteBuffer::readInt32(bool *error) {
if (_position + 4 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read int32 error");
return 0;
}
int32_t result = ((buffer[_position] & 0xff)) |
((buffer[_position + 1] & 0xff) << 8) |
((buffer[_position + 2] & 0xff) << 16) |
((buffer[_position + 3] & 0xff) << 24);
_position += 4;
return result;
}
uint32_t NativeByteBuffer::readUint32(bool *error) {
return (uint32_t) readInt32(error);
}
uint64_t NativeByteBuffer::readUint64(bool *error) {
return (uint64_t) readInt64(error);
}
int32_t NativeByteBuffer::readBigInt32(bool *error) {
if (_position + 4 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read big int32 error");
return 0;
}
int32_t result = ((buffer[_position] & 0xff) << 24) |
((buffer[_position + 1] & 0xff) << 16) |
((buffer[_position + 2] & 0xff) << 8) |
((buffer[_position + 3] & 0xff));
_position += 4;
return result;
}
int64_t NativeByteBuffer::readInt64(bool *error) {
if (_position + 4 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read int64 error");
return 0;
}
int64_t result = ((int64_t) (buffer[_position] & 0xff)) |
((int64_t) (buffer[_position + 1] & 0xff) << 8) |
((int64_t) (buffer[_position + 2] & 0xff) << 16) |
((int64_t) (buffer[_position + 3] & 0xff) << 24) |
((int64_t) (buffer[_position + 4] & 0xff) << 32) |
((int64_t) (buffer[_position + 5] & 0xff) << 40) |
((int64_t) (buffer[_position + 6] & 0xff) << 48) |
((int64_t) (buffer[_position + 7] & 0xff) << 56);
_position += 8;
return result;
}
uint8_t NativeByteBuffer::readByte(bool *error) {
if (_position + 1 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read byte error");
return 0;
}
return buffer[_position++];
}
bool NativeByteBuffer::readBool(bool *error) {
uint32_t consructor = readUint32(error);
if (consructor == 0x997275b5) {
return true;
} else if (consructor == 0xbc799737) {
return false;
}
if (error != nullptr) {
*error = true;
DEBUG_E("read bool error");
}
return false;
}
void NativeByteBuffer::readBytes(uint8_t *b, uint32_t length, bool *error) {
if (_position + length > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read bytes error");
return;
}
memcpy(b, buffer + _position, length);
_position += length;
}
ByteArray *NativeByteBuffer::readBytes(uint32_t length, bool *error) {
if (_position + length > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read bytes error");
return nullptr;
}
ByteArray *byteArray = new ByteArray(length);
memcpy(byteArray->bytes, buffer + _position, sizeof(uint8_t) * length);
_position += length;
return byteArray;
}
std::string NativeByteBuffer::readString(bool *error) {
uint32_t sl = 1;
if (_position + 1 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read string error");
return std::string("");
}
uint32_t l = buffer[_position++];
if (l >= 254) {
if (_position + 3 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read string error");
return std::string("");
}
l = buffer[_position] | (buffer[_position + 1] << 8) | (buffer[_position + 2] << 16);
_position += 3;
sl = 4;
}
uint32_t addition = (l + sl) % 4;
if (addition != 0) {
addition = 4 - addition;
}
if (_position + l + addition > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read string error");
return std::string("");
}
std::string result = std::string((const char *) (buffer + _position), l);
_position += l + addition;
return result;
}
ByteArray *NativeByteBuffer::readByteArray(bool *error) {
uint32_t sl = 1;
if (_position + 1 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read byte array error");
return nullptr;
}
uint32_t l = buffer[_position++];
if (l >= 254) {
if (_position + 3 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read byte array error");
return nullptr;
}
l = buffer[_position] | (buffer[_position + 1] << 8) | (buffer[_position + 2] << 16);
_position += 3;
sl = 4;
}
uint32_t addition = (l + sl) % 4;
if (addition != 0) {
addition = 4 - addition;
}
if (_position + l + addition > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read byte array error");
return nullptr;
}
ByteArray *result = new ByteArray(l);
memcpy(result->bytes, buffer + _position, sizeof(uint8_t) * l);
_position += l + addition;
return result;
}
NativeByteBuffer *NativeByteBuffer::readByteBuffer(bool copy, bool *error) {
uint32_t sl = 1;
if (_position + 1 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read byte buffer error");
return nullptr;
}
uint32_t l = buffer[_position++];
if (l >= 254) {
if (_position + 3 > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read byte buffer error");
return nullptr;
}
l = buffer[_position] | (buffer[_position + 1] << 8) | (buffer[_position + 2] << 16);
_position += 3;
sl = 4;
}
uint32_t addition = (l + sl) % 4;
if (addition != 0) {
addition = 4 - addition;
}
if (_position + l + addition > _limit) {
if (error != nullptr) {
*error = true;
}
DEBUG_E("read byte buffer error");
return nullptr;
}
NativeByteBuffer *result = nullptr;
if (copy) {
result = BuffersStorage::getInstance().getFreeBuffer(l);
memcpy(result->buffer, buffer + _position, sizeof(uint8_t) * l);
} else {
result = new NativeByteBuffer(buffer + _position, l);
}
_position += l + addition;
return result;
}
double NativeByteBuffer::readDouble(bool *error) {
double value;
int64_t value2 = readInt64(error);
memcpy(&value, &value2, sizeof(double));
return value;
}
void NativeByteBuffer::reuse() {
if (sliced) {
return;
}
BuffersStorage::getInstance().reuseFreeBuffer(this);
}
#ifdef ANDROID
jobject NativeByteBuffer::getJavaByteBuffer() {
if (javaByteBuffer == nullptr && javaVm != nullptr) {
JNIEnv *env = 0;
if (javaVm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
DEBUG_E("can't get jnienv");
exit(1);
}
javaByteBuffer = env->NewDirectByteBuffer(buffer, _capacity);
if (javaByteBuffer == nullptr) {
DEBUG_E("can't allocate NativeByteBuffer buffer");
exit(1);
}
jobject globalRef = env->NewGlobalRef(javaByteBuffer);
env->DeleteLocalRef(javaByteBuffer);
javaByteBuffer = globalRef;
}
return javaByteBuffer;
}
#endif
-107
View File
@@ -1,107 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef NATIVEBYTEBUFFER_H
#define NATIVEBYTEBUFFER_H
#include <stdint.h>
#include <string>
#ifdef ANDROID
#include <jni.h>
#endif
class ByteArray;
class NativeByteBuffer {
public:
NativeByteBuffer(uint32_t size);
NativeByteBuffer(bool calculate);
NativeByteBuffer(uint8_t *buff, uint32_t length);
~NativeByteBuffer();
uint32_t position();
void position(uint32_t position);
uint32_t limit();
void limit(uint32_t limit);
uint32_t capacity();
uint32_t remaining();
bool hasRemaining();
void rewind();
void compact();
void flip();
void clear();
void skip(uint32_t length);
void clearCapacity();
uint8_t *bytes();
void writeInt32(int32_t x, bool *error);
void writeInt64(int64_t x, bool *error);
void writeBool(bool value, bool *error);
void writeBytes(uint8_t *b, uint32_t length, bool *error);
void writeBytes(uint8_t *b, uint32_t offset, uint32_t length, bool *error);
void writeBytes(ByteArray *b, bool *error);
void writeBytes(NativeByteBuffer *b, bool *error);
void writeByte(uint8_t i, bool *error);
void writeString(std::string s, bool *error);
void writeByteArray(uint8_t *b, uint32_t offset, uint32_t length, bool *error);
void writeByteArray(uint8_t *b, uint32_t length, bool *error);
void writeByteArray(NativeByteBuffer *b, bool *error);
void writeByteArray(ByteArray *b, bool *error);
void writeDouble(double d, bool *error);
void writeInt32(int32_t x);
void writeInt64(int64_t x);
void writeBool(bool value);
void writeBytes(uint8_t *b, uint32_t length);
void writeBytes(uint8_t *b, uint32_t offset, uint32_t length);
void writeBytes(ByteArray *b);
void writeBytes(NativeByteBuffer *b);
void writeByte(uint8_t i);
void writeString(std::string s);
void writeByteArray(uint8_t *b, uint32_t offset, uint32_t length);
void writeByteArray(uint8_t *b, uint32_t length);
void writeByteArray(NativeByteBuffer *b);
void writeByteArray(ByteArray *b);
void writeDouble(double d);
uint32_t readUint32(bool *error);
uint64_t readUint64(bool *error);
int32_t readInt32(bool *error);
int32_t readBigInt32(bool *error);
int64_t readInt64(bool *error);
uint8_t readByte(bool *error);
bool readBool(bool *error);
void readBytes(uint8_t *b, uint32_t length, bool *error);
ByteArray *readBytes(uint32_t length, bool *error);
std::string readString(bool *error);
ByteArray *readByteArray(bool *error);
NativeByteBuffer *readByteBuffer(bool copy, bool *error);
double readDouble(bool *error);
void reuse();
#ifdef ANDROID
jobject getJavaByteBuffer();
#endif
private:
void writeBytesInternal(uint8_t *b, uint32_t offset, uint32_t length);
uint8_t *buffer = nullptr;
bool calculateSizeOnly = false;
bool sliced = false;
uint32_t _position = 0;
uint32_t _limit = 0;
uint32_t _capacity = 0;
bool bufferOwner = true;
#ifdef ANDROID
jobject javaByteBuffer = nullptr;
#endif
};
#endif
-69
View File
@@ -1,69 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#include <algorithm>
#include "Request.h"
#include "TLObject.h"
#include "MTProtoScheme.h"
#include "ConnectionsManager.h"
Request::Request(int32_t token, ConnectionType type, uint32_t flags, uint32_t datacenter, onCompleteFunc completeFunc, onQuickAckFunc quickAckFunc) {
requestToken = token;
connectionType = type;
requestFlags = flags;
datacenterId = datacenter;
onCompleteRequestCallback = completeFunc;
onQuickAckCallback = quickAckFunc;
}
Request::~Request() {
#ifdef ANDROID
if (ptr1 != nullptr) {
jniEnv->DeleteGlobalRef(ptr1);
ptr1 = nullptr;
}
if (ptr2 != nullptr) {
jniEnv->DeleteGlobalRef(ptr2);
ptr2 = nullptr;
}
#endif
}
void Request::addRespondMessageId(int64_t id) {
respondsToMessageIds.push_back(messageId);
}
bool Request::respondsToMessageId(int64_t id) {
return messageId == id || std::find(respondsToMessageIds.begin(), respondsToMessageIds.end(), id) != respondsToMessageIds.end();
}
void Request::clear(bool time) {
messageId = 0;
messageSeqNo = 0;
connectionToken = 0;
if (time) {
startTime = 0;
minStartTime = 0;
}
}
void Request::onComplete(TLObject *result, TL_error *error) {
if (onCompleteRequestCallback != nullptr && (result != nullptr || error != nullptr)) {
onCompleteRequestCallback(result, error);
}
}
void Request::onQuickAck() {
if (onQuickAckCallback != nullptr) {
onQuickAckCallback();
}
}
TLObject *Request::getRpcRequest() {
return rpcRequest.get();
}
-69
View File
@@ -1,69 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef REQUEST_H
#define REQUEST_H
#include <stdint.h>
#include <vector>
#include <bits/unique_ptr.h>
#include "Defines.h"
#ifdef ANDROID
#include <jni.h>
#endif
class TLObject;
class TL_error;
class Request {
public:
Request(int32_t token, ConnectionType type, uint32_t flags, uint32_t datacenter, onCompleteFunc completeFunc, onQuickAckFunc quickAckFunc);
~Request();
int64_t messageId = 0;
int32_t messageSeqNo = 0;
uint32_t datacenterId = 0;
uint32_t connectionToken = 0;
int32_t requestToken;
uint32_t retryCount = 0;
bool failedBySalt = false;
int32_t failedByFloodWait = 0;
ConnectionType connectionType;
uint32_t requestFlags;
bool completed = false;
bool cancelled = false;
bool isInitRequest = false;
int32_t serializedLength = 0;
int32_t startTime = 0;
int32_t minStartTime = 0;
int32_t lastResendTime = 0;
uint32_t serverFailureCount = 0;
TLObject *rawRequest;
std::unique_ptr<TLObject> rpcRequest;
onCompleteFunc onCompleteRequestCallback;
onQuickAckFunc onQuickAckCallback;
void addRespondMessageId(int64_t id);
bool respondsToMessageId(int64_t id);
void clear(bool time);
void onComplete(TLObject *result, TL_error *error);
void onQuickAck();
TLObject *getRpcRequest();
#ifdef ANDROID
jobject ptr1 = nullptr;
jobject ptr2 = nullptr;
#endif
private:
std::vector<int64_t> respondsToMessageIds;
};
#endif
-38
View File
@@ -1,38 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#include "TLObject.h"
#include "NativeByteBuffer.h"
thread_local NativeByteBuffer *sizeCalculatorBuffer = new NativeByteBuffer(true);
TLObject::~TLObject() {
}
void TLObject::readParams(NativeByteBuffer *stream, bool &error) {
}
void TLObject::serializeToStream(NativeByteBuffer *stream) {
}
TLObject *TLObject::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) {
return nullptr;
}
uint32_t TLObject::getObjectSize() {
sizeCalculatorBuffer->clearCapacity();
serializeToStream(sizeCalculatorBuffer);
return sizeCalculatorBuffer->capacity();
}
bool TLObject::isNeedLayer() {
return false;
}
-27
View File
@@ -1,27 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef TLOBJECT_H
#define TLOBJECT_H
#include <stdint.h>
class NativeByteBuffer;
class TLObject {
public:
virtual ~TLObject();
virtual void readParams(NativeByteBuffer *stream, bool &error);
virtual void serializeToStream(NativeByteBuffer *stream);
virtual TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error);
uint32_t getObjectSize();
virtual bool isNeedLayer();
};
#endif
-61
View File
@@ -1,61 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#include "Timer.h"
#include "FileLog.h"
#include "EventObject.h"
#include "ConnectionsManager.h"
Timer::Timer(std::function<void()> function) {
eventObject = new EventObject(this, EventObjectTypeTimer);
callback = function;
}
Timer::~Timer() {
stop();
if (eventObject != nullptr) {
delete eventObject;
eventObject = nullptr;
}
}
void Timer::start() {
if (started || timeout == 0) {
return;
}
started = true;
ConnectionsManager::getInstance().scheduleEvent(eventObject, timeout);
}
void Timer::stop() {
if (!started) {
return;
}
started = false;
ConnectionsManager::getInstance().removeEvent(eventObject);
}
void Timer::setTimeout(uint32_t ms, bool repeat) {
if (ms == timeout) {
return;
}
repeatable = repeat;
timeout = ms;
if (started) {
ConnectionsManager::getInstance().removeEvent(eventObject);
ConnectionsManager::getInstance().scheduleEvent(eventObject, timeout);
}
}
void Timer::onEvent() {
callback();
DEBUG_D("timer(%p) call", this);
if (started && repeatable && timeout != 0) {
ConnectionsManager::getInstance().scheduleEvent(eventObject, timeout);
}
}
-40
View File
@@ -1,40 +0,0 @@
/*
* This is the source code of tgnet library v. 1.0
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2015.
*/
#ifndef TIMER_H
#define TIMER_H
#include <stdint.h>
#include <functional>
#include <sys/epoll.h>
class EventObject;
class Timer {
public:
Timer(std::function<void()> function);
~Timer();
void start();
void stop();
void setTimeout(uint32_t ms, bool repeat);
private:
void onEvent();
bool started = false;
bool repeatable = false;
uint32_t timeout = 0;
std::function<void()> callback;
EventObject *eventObject;
friend class EventObject;
};
#endif
@@ -275,7 +275,7 @@ public class ApplicationLoader extends Application {
ConnectionsManager.getInstance().init(BuildVars.BUILD_VERSION, TLRPC.LAYER, BuildVars.APP_ID, deviceModel, systemVersion, appVersion, langCode, configPath, FileLog.getNetworkLogPath(), UserConfig.getClientUserId(), enablePushConnection);
if (UserConfig.getCurrentUser() != null) {
MessagesController.getInstance().putUser(UserConfig.getCurrentUser(), true);
ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.getCurrentUser().phone);
//ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.getCurrentUser().phone);
MessagesController.getInstance().getBlockedUsers(true);
SendMessagesHelper.getInstance().checkUnsentMessages();
}
@@ -298,7 +298,7 @@ public class ApplicationLoader extends Application {
applicationContext = getApplicationContext();
NativeLoader.initNativeLibs(ApplicationLoader.applicationContext);
ConnectionsManager.native_setJava(Build.VERSION.SDK_INT == 14 || Build.VERSION.SDK_INT == 15);
//ConnectionsManager.native_setJava(Build.VERSION.SDK_INT == 14 || Build.VERSION.SDK_INT == 15);
new ForegroundDetector(this);
// EDIT BY MR - create a MrMailbox object; as android stops the App by just killing it, we do never call MrMailboxUnref()
@@ -787,13 +787,13 @@ public class ContactsController {
}
}*/
final HashMap<Integer, Contact> contactsMapToSave = new HashMap<>(contactsMap);
//final HashMap<Integer, Contact> contactsMapToSave = new HashMap<>(contactsMap);
completedRequestsCount = 0;
final int count = (int) Math.ceil(toImport.size() / 500.0f);
for (int a = 0; a < count; a++) {
ArrayList<TLRPC.TL_inputPhoneContact> finalToImport = new ArrayList<>();
finalToImport.addAll(toImport.subList(a * 500, Math.min((a + 1) * 500, toImport.size())));
TLRPC.TL_contacts_importContacts req = new TLRPC.TL_contacts_importContacts();
/*TLRPC.TL_contacts_importContacts req = new TLRPC.TL_contacts_importContacts();
req.contacts = finalToImport;
req.replace = false;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@@ -811,15 +811,15 @@ public class ContactsController {
}
if (completedRequestsCount == count && !contactsMapToSave.isEmpty()) {
//MessagesStorage.getInstance().putCachedPhoneBook(contactsMapToSave);
MessagesStorage.getInstance().putCachedPhoneBook(contactsMapToSave);
}
/*if (BuildVars.DEBUG_VERSION) {
if (BuildVars.DEBUG_VERSION) {
for (TLRPC.User user : res.users) {
FileLog.e("tmessages", "received user " + user.first_name + " " + user.last_name + " " + user.phone);
}
}*/
//MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true);
}
MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true);
ArrayList<TLRPC.TL_contact> cArr = new ArrayList<>();
for (int a = 0; a < res.imported.size(); a++) {
TLRPC.TL_contact contact = new TLRPC.TL_contact();
@@ -849,7 +849,7 @@ public class ContactsController {
});
}
}
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagCanCompress);
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagCanCompress);*/
}
} else {
Utilities.stageQueue.postRunnable(new Runnable() {
@@ -916,7 +916,7 @@ public class ContactsController {
//MessagesStorage.getInstance().getContacts();
} else {
FileLog.e("tmessages", "load contacts from server");
TLRPC.TL_contacts_getContacts req = new TLRPC.TL_contacts_getContacts();
/*TLRPC.TL_contacts_getContacts req = new TLRPC.TL_contacts_getContacts();
req.hash = cacheEmpty ? "" : UserConfig.contactsHash;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
@@ -944,7 +944,7 @@ public class ContactsController {
processLoadedContacts(res.contacts, res.users, 0);
}
}
});
});*/
}
}
@@ -1676,20 +1676,20 @@ public class ContactsController {
/*if (BuildVars.DEBUG_VERSION) {
FileLog.e("tmessages", "add contact " + user.first_name + " " + user.last_name + " " + user.phone);
}*/
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error != null) {
return;
}
final TLRPC.TL_contacts_importedContacts res = (TLRPC.TL_contacts_importedContacts) response;
//MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true);
MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true);
/*if (BuildVars.DEBUG_VERSION) {
if (BuildVars.DEBUG_VERSION) {
for (TLRPC.User user : res.users) {
FileLog.e("tmessages", "received user " + user.first_name + " " + user.last_name + " " + user.phone);
}
}*/
}
for (int a = 0; a < res.users.size(); a++) {
final TLRPC.User u = res.users.get(a);
@@ -1735,7 +1735,7 @@ public class ContactsController {
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagCanCompress);
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagCanCompress);*/
}
public void deleteContact(final ArrayList<TLRPC.User> users) {
@@ -1752,7 +1752,7 @@ public class ContactsController {
uids.add(user.id);
req.id.add(inputUser);
}
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error != null) {
@@ -1802,7 +1802,7 @@ public class ContactsController {
}
});
}
});
});*/
}
public void reloadContactsStatuses() {
@@ -1811,7 +1811,7 @@ public class ContactsController {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("needGetStatuses", true).commit();
TLRPC.TL_contacts_getStatuses req = new TLRPC.TL_contacts_getStatuses();
/*TLRPC.TL_contacts_getStatuses req = new TLRPC.TL_contacts_getStatuses();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, TLRPC.TL_error error) {
@@ -1852,13 +1852,13 @@ public class ContactsController {
});
}
}
});
});*/
}
public void loadPrivacySettings() {
if (loadingDeleteInfo == 0) {
loadingDeleteInfo = 1;
TLRPC.TL_account_getAccountTTL req = new TLRPC.TL_account_getAccountTTL();
/*TLRPC.TL_account_getAccountTTL req = new TLRPC.TL_account_getAccountTTL();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
@@ -1876,11 +1876,11 @@ public class ContactsController {
}
});
}
});
});*/
}
if (loadingLastSeenInfo == 0) {
loadingLastSeenInfo = 1;
TLRPC.TL_account_getPrivacy req = new TLRPC.TL_account_getPrivacy();
/*TLRPC.TL_account_getPrivacy req = new TLRPC.TL_account_getPrivacy();
req.key = new TLRPC.TL_inputPrivacyKeyStatusTimestamp();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
@@ -1900,11 +1900,11 @@ public class ContactsController {
}
});
}
});
});*/
}
if (loadingGroupInfo == 0) {
loadingGroupInfo = 1;
TLRPC.TL_account_getPrivacy req = new TLRPC.TL_account_getPrivacy();
/*TLRPC.TL_account_getPrivacy req = new TLRPC.TL_account_getPrivacy();
req.key = new TLRPC.TL_inputPrivacyKeyChatInvite();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
@@ -1924,7 +1924,7 @@ public class ContactsController {
}
});
}
});
});*/
}
NotificationCenter.getInstance().postNotificationName(NotificationCenter.privacyRulesUpdated);
}
@@ -24,7 +24,6 @@ public class FileLoadOperation {
private static class RequestInfo {
private int requestToken;
private int offset;
private TLRPC.TL_upload_file response;
}
private final static int stateIdle = 0;
@@ -345,10 +344,10 @@ public class FileLoadOperation {
if (delayedRequestInfos != null) {
for (int a = 0; a < delayedRequestInfos.size(); a++) {
RequestInfo requestInfo = delayedRequestInfos.get(a);
if (requestInfo.response != null) {
/*if (requestInfo.response != null) {
requestInfo.response.disableFree = false;
requestInfo.response.freeResources();
}
}*/
}
delayedRequestInfos.clear();
}
@@ -394,109 +393,7 @@ public class FileLoadOperation {
delegate.didFinishLoadingFile(FileLoadOperation.this, cacheFileFinal);
}
private void processRequestResult(RequestInfo requestInfo, TLRPC.TL_error error) {
requestInfos.remove(requestInfo);
if (error == null) {
try {
if (downloadedBytes != requestInfo.offset) {
if (state == stateDownloading) {
delayedRequestInfos.add(requestInfo);
requestInfo.response.disableFree = true;
}
return;
}
if (requestInfo.response.bytes == null || requestInfo.response.bytes.limit() == 0) {
onFinishLoadingFile();
return;
}
int currentBytesSize = requestInfo.response.bytes.limit();
downloadedBytes += currentBytesSize;
boolean finishedDownloading = currentBytesSize != currentDownloadChunkSize || (totalBytesCount == downloadedBytes || downloadedBytes % currentDownloadChunkSize != 0) && (totalBytesCount <= 0 || totalBytesCount <= downloadedBytes);
if (key != null) {
Utilities.aesIgeEncryption(requestInfo.response.bytes.buffer, key, iv, false, true, 0, requestInfo.response.bytes.limit());
if (finishedDownloading && bytesCountPadding != 0) {
requestInfo.response.bytes.limit(requestInfo.response.bytes.limit() - bytesCountPadding);
}
}
if (fileOutputStream != null) {
FileChannel channel = fileOutputStream.getChannel();
channel.write(requestInfo.response.bytes.buffer);
}
if (fiv != null) {
fiv.seek(0);
fiv.write(iv);
}
if (totalBytesCount > 0 && state == stateDownloading) {
delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float) downloadedBytes / (float) totalBytesCount));
}
for (int a = 0; a < delayedRequestInfos.size(); a++) {
RequestInfo delayedRequestInfo = delayedRequestInfos.get(a);
if (downloadedBytes == delayedRequestInfo.offset) {
delayedRequestInfos.remove(a);
processRequestResult(delayedRequestInfo, null);
delayedRequestInfo.response.disableFree = false;
delayedRequestInfo.response.freeResources();
break;
}
}
if (finishedDownloading) {
onFinishLoadingFile();
} else {
startDownloadRequest();
}
} catch (Exception e) {
cleanup();
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
FileLog.e("tmessages", e);
}
} else {
if (error.text.contains("FILE_MIGRATE_")) {
String errorMsg = error.text.replace("FILE_MIGRATE_", "");
Scanner scanner = new Scanner(errorMsg);
scanner.useDelimiter("");
Integer val;
try {
val = scanner.nextInt();
} catch (Exception e) {
val = null;
}
if (val == null) {
cleanup();
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
} else {
datacenter_id = val;
nextDownloadOffset = 0;
startDownloadRequest();
}
} else if (error.text.contains("OFFSET_INVALID")) {
if (downloadedBytes % currentDownloadChunkSize == 0) {
try {
onFinishLoadingFile();
} catch (Exception e) {
FileLog.e("tmessages", e);
cleanup();
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
}
} else {
cleanup();
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
}
} else if (error.text.contains("RETRY_LIMIT")) {
cleanup();
delegate.didFailedLoadingFile(FileLoadOperation.this, 2);
} else {
if (location != null) {
FileLog.e("tmessages", "" + location + " id = " + location.id + " local_id = " + location.local_id + " access_hash = " + location.access_hash + " volume_id = " + location.volume_id + " secret = " + location.secret);
}
cleanup();
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
}
}
}
private void startDownloadRequest() {
if (state != stateDownloading || totalBytesCount > 0 && nextDownloadOffset >= totalBytesCount || requestInfos.size() + delayedRequestInfos.size() >= currentMaxDownloadRequests) {
@@ -512,22 +409,22 @@ public class FileLoadOperation {
break;
}
boolean isLast = totalBytesCount <= 0 || a == count - 1 || totalBytesCount > 0 && nextDownloadOffset + currentDownloadChunkSize >= totalBytesCount;
TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile();
req.location = location;
req.offset = nextDownloadOffset;
req.limit = currentDownloadChunkSize;
//TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile();
//req.location = location;
//req.offset = nextDownloadOffset;
//req.limit = currentDownloadChunkSize;
nextDownloadOffset += currentDownloadChunkSize;
final RequestInfo requestInfo = new RequestInfo();
requestInfos.add(requestInfo);
requestInfo.offset = req.offset;
requestInfo.requestToken = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
requestInfo.offset = nextDownloadOffset;
requestInfo.requestToken = 0;/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
requestInfo.response = (TLRPC.TL_upload_file) response;
processRequestResult(requestInfo, error);
}
}, null, (isForceRequest ? ConnectionsManager.RequestFlagForceDownload : 0) | ConnectionsManager.RequestFlagFailOnServerErrors, datacenter_id, requestsCount % 2 == 0 ? ConnectionsManager.ConnectionTypeDownload : ConnectionsManager.ConnectionTypeDownload2, isLast);
}, null, (isForceRequest ? ConnectionsManager.RequestFlagForceDownload : 0) | ConnectionsManager.RequestFlagFailOnServerErrors, datacenter_id, requestsCount % 2 == 0 ? ConnectionsManager.ConnectionTypeDownload : ConnectionsManager.ConnectionTypeDownload2, isLast);*/
requestsCount++;
}
}
@@ -99,6 +99,7 @@ public class FileLoader {
return dir;
}
/*
public void checkUploadNewDataAvailable(final String location, final boolean encrypted, final long finalSize) {
fileLoaderQueue.postRunnable(new Runnable() {
@Override
@@ -117,6 +118,7 @@ public class FileLoader {
}
});
}
*/
public void uploadFile(final String location, final boolean encrypted, final boolean small) {
uploadFile(location, encrypted, small, 0);
@@ -12,44 +12,23 @@ import android.app.Activity;
import android.content.SharedPreferences;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
public class FileUploadOperation {
private int uploadChunkSize = 1024 * 32;
private String uploadingFilePath;
public int state = 0;
private byte[] readBuffer;
public FileUploadOperationDelegate delegate;
private int requestToken = 0;
private int currentPartNum = 0;
private long currentFileId;
private boolean isLastPart = false;
private long totalFileSize = 0;
private int totalPartsCount = 0;
private long currentUploaded = 0;
private int saveInfoTimes = 0;
private byte[] key;
private byte[] iv;
private byte[] ivChange;
private boolean isEncrypted = false;
private int fingerprint = 0;
private boolean isBigFile = false;
private String fileKey;
private int estimatedSize = 0;
private int uploadStartTime = 0;
private FileInputStream stream;
private MessageDigest mdEnc = null;
private boolean started = false;
public interface FileUploadOperationDelegate {
void didFinishUploadingFile(FileUploadOperation operation, TLRPC.InputFile inputFile, TLRPC.InputEncryptedFile inputEncryptedFile, byte[] key, byte[] iv);
@@ -58,7 +37,6 @@ public class FileUploadOperation {
}
public FileUploadOperation(String location, boolean encrypted, int estimated) {
uploadingFilePath = location;
isEncrypted = encrypted;
estimatedSize = estimated;
}
@@ -68,16 +46,6 @@ public class FileUploadOperation {
}
public void start() {
if (state != 0) {
return;
}
state = 1;
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
startUploadRequest();
}
});
}
public void cancel() {
@@ -93,24 +61,9 @@ public class FileUploadOperation {
}
private void cleanup() {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("uploadinfo", Activity.MODE_PRIVATE);
preferences.edit().remove(fileKey + "_time").
remove(fileKey + "_size").
remove(fileKey + "_uploaded").
remove(fileKey + "_id").
remove(fileKey + "_iv").
remove(fileKey + "_key").
remove(fileKey + "_ivc").commit();
try {
if (stream != null) {
stream.close();
stream = null;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
/*
protected void checkNewDataAvailable(final long finalSize) {
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
@@ -130,292 +83,7 @@ public class FileUploadOperation {
}
});
}
*/
private void storeFileUploadInfo(SharedPreferences preferences) {
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(fileKey + "_time", uploadStartTime);
editor.putLong(fileKey + "_size", totalFileSize);
editor.putLong(fileKey + "_id", currentFileId);
editor.remove(fileKey + "_uploaded");
if (isEncrypted) {
editor.putString(fileKey + "_iv", Utilities.bytesToHex(iv));
editor.putString(fileKey + "_ivc", Utilities.bytesToHex(ivChange));
editor.putString(fileKey + "_key", Utilities.bytesToHex(key));
}
editor.commit();
}
private void startUploadRequest() {
if (state != 1) {
return;
}
TLObject finalRequest;
try {
started = true;
if (stream == null) {
File cacheFile = new File(uploadingFilePath);
stream = new FileInputStream(cacheFile);
if (estimatedSize != 0) {
totalFileSize = estimatedSize;
} else {
totalFileSize = cacheFile.length();
}
if (totalFileSize > 10 * 1024 * 1024) {
isBigFile = true;
} else {
try {
mdEnc = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
FileLog.e("tmessages", e);
}
}
uploadChunkSize = (int) Math.max(32, (totalFileSize + 1024 * 3000 - 1) / (1024 * 3000));
if (1024 % uploadChunkSize != 0) {
int chunkSize = 64;
while (uploadChunkSize > chunkSize) {
chunkSize *= 2;
}
uploadChunkSize = chunkSize;
}
uploadChunkSize *= 1024;
totalPartsCount = (int) (totalFileSize + uploadChunkSize - 1) / uploadChunkSize;
readBuffer = new byte[uploadChunkSize];
fileKey = Utilities.MD5(uploadingFilePath + (isEncrypted ? "enc" : ""));
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("uploadinfo", Activity.MODE_PRIVATE);
long fileSize = preferences.getLong(fileKey + "_size", 0);
uploadStartTime = (int)(System.currentTimeMillis() / 1000);
boolean rewrite = false;
if (estimatedSize == 0 && fileSize == totalFileSize) {
currentFileId = preferences.getLong(fileKey + "_id", 0);
int date = preferences.getInt(fileKey + "_time", 0);
long uploadedSize = preferences.getLong(fileKey + "_uploaded", 0);
if (isEncrypted) {
String ivString = preferences.getString(fileKey + "_iv", null);
String keyString = preferences.getString(fileKey + "_key", null);
if (ivString != null && keyString != null) {
key = Utilities.hexToBytes(keyString);
iv = Utilities.hexToBytes(ivString);
if (key != null && iv != null && key.length == 32 && iv.length == 32) {
ivChange = new byte[32];
System.arraycopy(iv, 0, ivChange, 0, 32);
} else {
rewrite = true;
}
} else {
rewrite = true;
}
}
if (!rewrite && date != 0) {
if (isBigFile && date < uploadStartTime - 60 * 60 * 24) {
date = 0;
} else if (!isBigFile && date < uploadStartTime - 60 * 60 * 1.5f) {
date = 0;
}
if (date != 0) {
if (uploadedSize > 0) {
currentUploaded = uploadedSize;
currentPartNum = (int) (uploadedSize / uploadChunkSize);
if (!isBigFile) {
for (int b = 0; b < currentUploaded / uploadChunkSize; b++) {
int read = stream.read(readBuffer);
int toAdd = 0;
if (isEncrypted && read % 16 != 0) {
toAdd += 16 - read % 16;
}
NativeByteBuffer sendBuffer = new NativeByteBuffer(read + toAdd);
if (read != uploadChunkSize || totalPartsCount == currentPartNum + 1) {
isLastPart = true;
}
sendBuffer.writeBytes(readBuffer, 0, read);
if (isEncrypted) {
for (int a = 0; a < toAdd; a++) {
sendBuffer.writeByte(0);
}
Utilities.aesIgeEncryption(sendBuffer.buffer, key, ivChange, true, true, 0, read + toAdd);
}
sendBuffer.rewind();
mdEnc.update(sendBuffer.buffer);
sendBuffer.reuse();
}
} else {
stream.skip(uploadedSize);
if (isEncrypted) {
String ivcString = preferences.getString(fileKey + "_ivc", null);
if (ivcString != null) {
ivChange = Utilities.hexToBytes(ivcString);
if (ivChange == null || ivChange.length != 32) {
rewrite = true;
currentUploaded = 0;
currentPartNum = 0;
}
} else {
rewrite = true;
currentUploaded = 0;
currentPartNum = 0;
}
}
}
} else {
rewrite = true;
}
}
} else {
rewrite = true;
}
} else {
rewrite = true;
}
if (rewrite) {
if (isEncrypted) {
iv = new byte[32];
key = new byte[32];
ivChange = new byte[32];
Utilities.random.nextBytes(iv);
Utilities.random.nextBytes(key);
System.arraycopy(iv, 0, ivChange, 0, 32);
}
currentFileId = Utilities.random.nextLong();
if (estimatedSize == 0) {
storeFileUploadInfo(preferences);
}
}
if (isEncrypted) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] arr = new byte[64];
System.arraycopy(key, 0, arr, 0, 32);
System.arraycopy(iv, 0, arr, 32, 32);
byte[] digest = md.digest(arr);
for (int a = 0; a < 4; a++) {
fingerprint |= ((digest[a] ^ digest[a + 4]) & 0xFF) << (a * 8);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
} else if (estimatedSize == 0) {
if (saveInfoTimes >= 4) {
saveInfoTimes = 0;
}
if (isBigFile && currentUploaded % (1024 * 1024) == 0 || !isBigFile && saveInfoTimes == 0) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("uploadinfo", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putLong(fileKey + "_uploaded", currentUploaded);
if (isEncrypted) {
editor.putString(fileKey + "_ivc", Utilities.bytesToHex(ivChange));
}
editor.commit();
}
saveInfoTimes++;
}
if (estimatedSize != 0) {
long size = stream.getChannel().size();
if (currentUploaded + uploadChunkSize > size) {
return;
}
}
int read = stream.read(readBuffer);
int toAdd = 0;
if (isEncrypted && read % 16 != 0) {
toAdd += 16 - read % 16;
}
NativeByteBuffer sendBuffer = new NativeByteBuffer(read + toAdd);
if (read != uploadChunkSize || estimatedSize == 0 && totalPartsCount == currentPartNum + 1) {
isLastPart = true;
}
sendBuffer.writeBytes(readBuffer, 0, read);
if (isEncrypted) {
for (int a = 0; a < toAdd; a++) {
sendBuffer.writeByte(0);
}
Utilities.aesIgeEncryption(sendBuffer.buffer, key, ivChange, true, true, 0, read + toAdd);
}
sendBuffer.rewind();
if (!isBigFile) {
mdEnc.update(sendBuffer.buffer);
}
if (isBigFile) {
TLRPC.TL_upload_saveBigFilePart req = new TLRPC.TL_upload_saveBigFilePart();
req.file_part = currentPartNum;
req.file_id = currentFileId;
if (estimatedSize != 0) {
req.file_total_parts = -1;
} else {
req.file_total_parts = totalPartsCount;
}
req.bytes = sendBuffer;
finalRequest = req;
} else {
TLRPC.TL_upload_saveFilePart req = new TLRPC.TL_upload_saveFilePart();
req.file_part = currentPartNum;
req.file_id = currentFileId;
req.bytes = sendBuffer;
finalRequest = req;
}
currentUploaded += read;
} catch (Exception e) {
FileLog.e("tmessages", e);
delegate.didFailedUploadingFile(this);
cleanup();
return;
}
requestToken = ConnectionsManager.getInstance().sendRequest(finalRequest, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
requestToken = 0;
if (error == null) {
if (response instanceof TLRPC.TL_boolTrue) {
currentPartNum++;
delegate.didChangedUploadProgress(FileUploadOperation.this, currentUploaded / (float) totalFileSize);
if (isLastPart) {
state = 3;
if (key == null) {
TLRPC.InputFile result;
if (isBigFile) {
result = new TLRPC.TL_inputFileBig();
} else {
result = new TLRPC.TL_inputFile();
result.md5_checksum = String.format(Locale.US, "%32s", new BigInteger(1, mdEnc.digest()).toString(16)).replace(' ', '0');
}
result.parts = currentPartNum;
result.id = currentFileId;
result.name = uploadingFilePath.substring(uploadingFilePath.lastIndexOf("/") + 1);
delegate.didFinishUploadingFile(FileUploadOperation.this, result, null, null, null);
cleanup();
} else {
TLRPC.InputEncryptedFile result;
/*if (isBigFile) {
result = new TLRPC.TL_inputEncryptedFileBigUploaded();
} else */ {
result = new TLRPC.TL_inputEncryptedFileUploaded();
result.md5_checksum = String.format(Locale.US, "%32s", new BigInteger(1, mdEnc.digest()).toString(16)).replace(' ', '0');
}
result.parts = currentPartNum;
result.id = currentFileId;
result.key_fingerprint = fingerprint;
delegate.didFinishUploadingFile(FileUploadOperation.this, null, result, key, iv);
cleanup();
}
} else {
startUploadRequest();
}
} else {
delegate.didFailedUploadingFile(FileUploadOperation.this);
cleanup();
}
} else {
delegate.didFailedUploadingFile(FileUploadOperation.this);
cleanup();
}
}
}, 0, ConnectionsManager.ConnectionTypeUpload);
}
}
@@ -1,70 +0,0 @@
/*
* This is the source code of Telegram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package org.telegram.messenger;
import org.telegram.tgnet.SerializedData;
public class MessageKeyData {
public byte[] aesKey;
public byte[] aesIv;
public static MessageKeyData generateMessageKeyData(byte[] authKey, byte[] messageKey, boolean incoming) {
MessageKeyData keyData = new MessageKeyData();
if (authKey == null || authKey.length == 0) {
keyData.aesIv = null;
keyData.aesKey = null;
return keyData;
}
int x = incoming ? 8 : 0;
SerializedData data = new SerializedData();
data.writeBytes(messageKey);
data.writeBytes(authKey, x, 32);
byte[] sha1_a = Utilities.computeSHA1(data.toByteArray());
data.cleanup();
data = new SerializedData();
data.writeBytes(authKey, 32 + x, 16);
data.writeBytes(messageKey);
data.writeBytes(authKey, 48 + x, 16);
byte[] sha1_b = Utilities.computeSHA1(data.toByteArray());
data.cleanup();
data = new SerializedData();
data.writeBytes(authKey, 64 + x, 32);
data.writeBytes(messageKey);
byte[] sha1_c = Utilities.computeSHA1(data.toByteArray());
data.cleanup();
data = new SerializedData();
data.writeBytes(messageKey);
data.writeBytes(authKey, 96 + x, 32);
byte[] sha1_d = Utilities.computeSHA1(data.toByteArray());
data.cleanup();
data = new SerializedData();
data.writeBytes(sha1_a, 0, 8);
data.writeBytes(sha1_b, 8, 12);
data.writeBytes(sha1_c, 4, 12);
keyData.aesKey = data.toByteArray();
data.cleanup();
data = new SerializedData();
data.writeBytes(sha1_a, 8, 12);
data.writeBytes(sha1_b, 0, 8);
data.writeBytes(sha1_c, 16, 4);
data.writeBytes(sha1_d, 0, 8);
keyData.aesIv = data.toByteArray();
data.cleanup();
return keyData;
}
}
@@ -23,8 +23,6 @@ import org.telegram.messenger.query.MessagesQuery;
import org.telegram.messenger.query.SearchQuery;
import org.telegram.messenger.query.StickersQuery;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.SerializedData;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
@@ -36,7 +34,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
@@ -78,7 +75,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
private SparseArray<ArrayList<Integer>> channelViewsToSend = new SparseArray<>();
private SparseArray<ArrayList<Integer>> channelViewsToReload = new SparseArray<>();
private long lastViewsCheckTime;
private HashMap<Integer, ArrayList<TLRPC.Updates>> updatesQueueChannels = new HashMap<>();
private HashMap<Integer, Long> updatesStartWaitTimeChannels = new HashMap<>();
@@ -113,7 +109,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
private Runnable currentDeleteTaskRunnable = null;
public boolean loadingDialogs = false;
private boolean migratingDialogs = false;
public boolean dialogsEndReached = false;
public boolean gettingDifference = false;
public boolean updatingState = false;
@@ -154,10 +149,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public static final int UPDATE_MASK_SEND_STATE = 4096;
public static final int UPDATE_MASK_CHANNEL = 8192;
public static final int UPDATE_MASK_CHAT_ADMINS = 16384;
public static final int UPDATE_MASK_ALL = UPDATE_MASK_AVATAR | UPDATE_MASK_STATUS | UPDATE_MASK_NAME | UPDATE_MASK_CHAT_AVATAR | UPDATE_MASK_CHAT_NAME | UPDATE_MASK_CHAT_MEMBERS | UPDATE_MASK_USER_PRINT | UPDATE_MASK_USER_PHONE | UPDATE_MASK_READ_DIALOG_MESSAGE | UPDATE_MASK_PHONE;
public static class PrintingUser {
public long lastTime;
public int userId;
public TLRPC.SendMessageAction action;
}
@@ -232,45 +225,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
}
public void updateConfig(final TLRPC.TL_config config) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
//maxBroadcastCount = config.broadcast_size_max;
maxMegagroupCount = config.megagroup_size_max;
maxGroupCount = config.chat_size_max;
groupBigSize = config.chat_big_size;
disabledFeatures = config.disabled_features;
maxEditTime = config.edit_time_limit;
ratingDecay = config.rating_e_decay;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("maxGroupCount", maxGroupCount);
//editor.putInt("maxBroadcastCount", maxBroadcastCount);
editor.putInt("maxMegagroupCount", maxMegagroupCount);
editor.putInt("groupBigSize", groupBigSize);
editor.putInt("maxEditTime", maxEditTime);
editor.putInt("ratingDecay", ratingDecay);
try {
SerializedData data = new SerializedData();
data.writeInt32(disabledFeatures.size());
for (TLRPC.TL_disabledFeature disabledFeature : disabledFeatures) {
disabledFeature.serializeToStream(data);
}
String string = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT);
if (string.length() != 0) {
editor.putString("disabledFeatures", string);
}
} catch (Exception e) {
editor.remove("disabledFeatures");
FileLog.e("tmessages", e);
}
editor.commit();
}
});
}
public static boolean isFeatureEnabled(String feature, BaseFragment fragment) {
if (feature == null || feature.length() == 0 || getInstance().disabledFeatures.isEmpty() || fragment == null) {
return true;
@@ -310,17 +264,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
return getInputUser(user);
}
public static TLRPC.InputChannel getInputChannel(TLRPC.Chat chat) {
if (chat instanceof TLRPC.TL_channel || chat instanceof TLRPC.TL_channelForbidden) {
TLRPC.InputChannel inputChat = new TLRPC.TL_inputChannel();
inputChat.channel_id = chat.id;
inputChat.access_hash = chat.access_hash;
return inputChat;
} else {
return new TLRPC.TL_inputChannelEmpty();
}
}
public static TLRPC.InputPeer getInputPeer(int id) {
TLRPC.InputPeer inputPeer;
if (id < 0) {
@@ -375,7 +318,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
req.crop = new TLRPC.TL_inputPhotoCropAuto();
req.file = file;
req.geo_point = new TLRPC.TL_inputGeoPointEmpty();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
@@ -416,7 +359,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
});
}
}
});
});*/
}
} else if (id == NotificationCenter.FileDidFailUpload) {
final String location = (String) args[0];
@@ -524,7 +467,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
ConnectionsManager.getInstance().setIsUpdating(false);
//ConnectionsManager.getInstance().setIsUpdating(false);
updatesQueueChannels.clear();
updatesStartWaitTimeChannels.clear();
gettingDifferenceChannels.clear();
@@ -763,7 +706,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
req.offset = offset;
req.max_id = (int) max_id;
req.user_id = getInputUser(user);
int reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
int reqId = 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
@@ -771,7 +714,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
processLoadedUserPhotos(res, did, offset, count, max_id, false, classGuid);
}
}
});
});*/
ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);
} else if (did < 0) {
TLRPC.TL_messages_search req = new TLRPC.TL_messages_search();
@@ -781,7 +724,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
req.max_id = (int) max_id;
req.q = "";
req.peer = MessagesController.getInputPeer(did);
int reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
int reqId = 0;/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
@@ -799,7 +742,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
processLoadedUserPhotos(res, did, offset, count, max_id, false, classGuid);
}
}
});
});*/
ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);
}
}
@@ -819,7 +762,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded);
TLRPC.TL_contacts_block req = new TLRPC.TL_contacts_block();
req.id = getInputUser(user);
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
@@ -828,7 +771,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
//MessagesStorage.getInstance().putBlockedUsers(ids, false);
}
}
});
});*/
}
public void unblockUser(int user_id) {
@@ -840,12 +783,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter
blockedUsers.remove((Integer) user.id);
req.id = getInputUser(user);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded);
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
//MessagesStorage.getInstance().deleteBlockedUser(user.id);
}
});
});*/
}
public void getBlockedUsers(boolean cache) {
@@ -859,7 +802,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
TLRPC.TL_contacts_getBlocked req = new TLRPC.TL_contacts_getBlocked();
req.offset = 0;
req.limit = 200;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
ArrayList<Integer> blocked = new ArrayList<>();
@@ -875,106 +818,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
processLoadedBlockedUsers(blocked, users, false);
}
});
});*/
}
}
public void processLoadedBlockedUsers(final ArrayList<Integer> ids, final ArrayList<TLRPC.User> users, final boolean cache) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (users != null) {
putUsers(users, cache);
}
loadingBlockedUsers = false;
if (ids.isEmpty() && cache && !UserConfig.blockedUsersLoaded) {
getBlockedUsers(false);
return;
} else if (!cache) {
UserConfig.blockedUsersLoaded = true;
UserConfig.saveConfig(false);
}
blockedUsers = ids;
NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded);
}
});
}
public void deleteUserPhoto(TLRPC.InputPhoto photo) {
if (photo == null) {
TLRPC.TL_photos_updateProfilePhoto req = new TLRPC.TL_photos_updateProfilePhoto();
req.id = new TLRPC.TL_inputPhotoEmpty();
req.crop = new TLRPC.TL_inputPhotoCropAuto();
UserConfig.getCurrentUser().photo = new TLRPC.TL_userProfilePhotoEmpty();
TLRPC.User user = getUser(UserConfig.getClientUserId());
if (user == null) {
user = UserConfig.getCurrentUser();
}
if (user == null) {
return;
}
user.photo = UserConfig.getCurrentUser().photo;
NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_ALL);
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
TLRPC.User user = getUser(UserConfig.getClientUserId());
if (user == null) {
user = UserConfig.getCurrentUser();
putUser(user, false);
} else {
UserConfig.setCurrentUser(user);
}
if (user == null) {
return;
}
//MessagesStorage.getInstance().clearUserPhotos(user.id);
ArrayList<TLRPC.User> users = new ArrayList<>();
users.add(user);
//MessagesStorage.getInstance().putUsersAndChats(users, null, false, true);
user.photo = (TLRPC.UserProfilePhoto) response;
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_ALL);
UserConfig.saveConfig(true);
}
});
}
}
});
} else {
TLRPC.TL_photos_deletePhotos req = new TLRPC.TL_photos_deletePhotos();
req.id.add(photo);
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
}
});
}
}
public void processLoadedUserPhotos(final TLRPC.photos_Photos res, final int did, final int offset, final int count, final long max_id, final boolean fromCache, final int classGuid) {
if (!fromCache) {
//MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true);
//MessagesStorage.getInstance().putDialogPhotos(did, res);
} else if (res == null || res.photos.isEmpty()) {
loadDialogPhotos(did, offset, count, max_id, false, classGuid);
return;
}
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
putUsers(res.users, fromCache);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogPhotosLoaded, did, offset, count, fromCache, classGuid, res.photos);
}
});
}
public void deleteMessages(ArrayList<Integer> messages, ArrayList<Long> randoms, TLRPC.EncryptedChat encryptedChat, final int channelId) {
}
@@ -997,7 +844,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
ArrayList<MediaController.SearchImage> arrayList = new ArrayList<>();
arrayList.add(searchImage);
//MessagesStorage.getInstance().putWebRecent(arrayList);
TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif();
/*TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif();
req.id = new TLRPC.TL_inputDocument();
req.id.id = searchImage.document.id;
req.id.access_hash = searchImage.document.access_hash;
@@ -1007,7 +854,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public void run(TLObject response, TLRPC.TL_error error) {
}
});
});*/
return searchImage;
}
@@ -1015,184 +862,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
//MessagesStorage.getInstance().loadChatInfo(chat_id, semaphore, force, false);
}
public void updateTimerProc() {
long currentTime = System.currentTimeMillis();
//checkDeletingTask(false);
if (UserConfig.isClientActivated()) {
if (ConnectionsManager.getInstance().getPauseTime() == 0 && ApplicationLoader.isScreenOn && !ApplicationLoader.mainInterfacePaused) {
if (statusSettingState != 1 && (lastStatusUpdateTime == 0 || Math.abs(System.currentTimeMillis() - lastStatusUpdateTime) >= 55000 || offlineSent)) {
statusSettingState = 1;
if (statusRequest != 0) {
ConnectionsManager.getInstance().cancelRequest(statusRequest, true);
}
TLRPC.TL_account_updateStatus req = new TLRPC.TL_account_updateStatus();
req.offline = false;
statusRequest = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
lastStatusUpdateTime = System.currentTimeMillis();
offlineSent = false;
statusSettingState = 0;
} else {
if (lastStatusUpdateTime != 0) {
lastStatusUpdateTime += 5000;
}
}
statusRequest = 0;
}
});
}
} else if (statusSettingState != 2 && !offlineSent && Math.abs(System.currentTimeMillis() - ConnectionsManager.getInstance().getPauseTime()) >= 2000) {
statusSettingState = 2;
if (statusRequest != 0) {
ConnectionsManager.getInstance().cancelRequest(statusRequest, true);
}
TLRPC.TL_account_updateStatus req = new TLRPC.TL_account_updateStatus();
req.offline = true;
statusRequest = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
offlineSent = true;
} else {
if (lastStatusUpdateTime != 0) {
lastStatusUpdateTime += 5000;
}
}
statusRequest = 0;
}
});
}
if (!updatesQueueChannels.isEmpty()) {
ArrayList<Integer> keys = new ArrayList<>(updatesQueueChannels.keySet());
for (int a = 0; a < keys.size(); a++) {
int key = keys.get(a);
Long updatesStartWaitTime = updatesStartWaitTimeChannels.get(key);
if (updatesStartWaitTime != null && updatesStartWaitTime + 1500 < currentTime) {
FileLog.e("tmessages", "QUEUE CHANNEL " + key + " UPDATES WAIT TIMEOUT - CHECK QUEUE");
//processChannelsUpdatesQueue(key, 0);
}
}
}
for (int a = 0; a < 3; a++) {
if (getUpdatesStartTime(a) != 0 && getUpdatesStartTime(a) + 1500 < currentTime) {
FileLog.e("tmessages", a + " QUEUE UPDATES WAIT TIMEOUT - CHECK QUEUE");
//processUpdatesQueue(a, 0);
}
}
}
if ((channelViewsToSend.size() != 0 || channelViewsToReload.size() != 0) && Math.abs(System.currentTimeMillis() - lastViewsCheckTime) >= 5000) {
lastViewsCheckTime = System.currentTimeMillis();
for (int b = 0; b < 2; b++) {
SparseArray<ArrayList<Integer>> array = b == 0 ? channelViewsToSend : channelViewsToReload;
if (array.size() == 0) {
continue;
}
for (int a = 0; a < array.size(); a++) {
final int key = array.keyAt(a);
final TLRPC.TL_messages_getMessagesViews req = new TLRPC.TL_messages_getMessagesViews();
req.peer = getInputPeer(key);
req.id = array.get(key);
req.increment = a == 0;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
TLRPC.Vector vector = (TLRPC.Vector) response;
final SparseArray<SparseIntArray> channelViews = new SparseArray<>();
SparseIntArray array = channelViews.get(key);
if (array == null) {
array = new SparseIntArray();
channelViews.put(key, array);
}
for (int a = 0; a < req.id.size(); a++) {
if (a >= vector.objects.size()) {
break;
}
array.put(req.id.get(a), (Integer) vector.objects.get(a));
}
//MessagesStorage.getInstance().putChannelViews(channelViews, req.peer instanceof TLRPC.TL_inputPeerChannel);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedMessagesViews, channelViews);
}
});
}
}
});
}
array.clear();
}
}
if (!onlinePrivacy.isEmpty()) {
ArrayList<Integer> toRemove = null;
int currentServerTime = ConnectionsManager.getInstance().getCurrentTime();
for (ConcurrentHashMap.Entry<Integer, Integer> entry : onlinePrivacy.entrySet()) {
if (entry.getValue() < currentServerTime - 30) {
if (toRemove == null) {
toRemove = new ArrayList<>();
}
toRemove.add(entry.getKey());
}
}
if (toRemove != null) {
for (Integer uid : toRemove) {
onlinePrivacy.remove(uid);
}
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_STATUS);
}
});
}
}
if (!printingUsers.isEmpty() || lastPrintingStringCount != printingUsers.size()) {
boolean updated = false;
ArrayList<Long> keys = new ArrayList<>(printingUsers.keySet());
for (int b = 0; b < keys.size(); b++) {
Long key = keys.get(b);
ArrayList<PrintingUser> arr = printingUsers.get(key);
for (int a = 0; a < arr.size(); a++) {
PrintingUser user = arr.get(a);
if (user.lastTime + 5900 < currentTime) {
updated = true;
arr.remove(user);
a--;
}
}
if (arr.isEmpty()) {
printingUsers.remove(key);
keys.remove(b);
b--;
}
}
updatePrintingStrings();
if (updated) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_USER_PRINT);
}
});
}
}
}
private void updatePrintingStrings() {
}
public void cancelTyping(int action, long dialog_id) {
}
@@ -1217,7 +886,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
reloadingWebpages.put(url, arrayList);
}
arrayList.addAll(messages);
TLRPC.TL_messages_getWebPagePreview req = new TLRPC.TL_messages_getWebPagePreview();
/*TLRPC.TL_messages_getWebPagePreview req = new TLRPC.TL_messages_getWebPagePreview();
req.message = url;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
@@ -1256,7 +925,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
});
}
});
});*/
}
}
@@ -1299,7 +968,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (!found) {
req.offset_peer = new TLRPC.TL_inputPeerEmpty();
}
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
@@ -1307,251 +976,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter
//processLoadedDialogs(dialogsRes, null, 0, count, 0, false, false);
}
}
});
});*/
}
}
protected void checkLastDialogMessage(final TLRPC.TL_dialog dialog, final TLRPC.InputPeer peer, long taskId) {
final int lower_id = (int) dialog.id;
if (lower_id == 0 || checkingLastMessagesDialogs.containsKey(lower_id)) {
return;
}
TLRPC.TL_messages_getHistory req = new TLRPC.TL_messages_getHistory();
req.peer = peer == null ? getInputPeer(lower_id) : peer;
if (req.peer == null) {
return;
}
req.limit = 1;
checkingLastMessagesDialogs.put(lower_id, true);
final long newTaskId;
if (taskId == 0) {
NativeByteBuffer data = null;
try {
data = new NativeByteBuffer(40 + peer.getObjectSize());
data.writeInt32(2);
data.writeInt64(dialog.id);
data.writeInt32(dialog.top_message);
data.writeInt32(dialog.read_inbox_max_id);
data.writeInt32(dialog.read_outbox_max_id);
data.writeInt32(dialog.unread_count);
data.writeInt32(dialog.last_message_date);
data.writeInt32(dialog.pts);
data.writeInt32(dialog.flags);
peer.serializeToStream(data);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
newTaskId = 0;//MessagesStorage.getInstance().createPendingTask(data);
} else {
newTaskId = taskId;
}
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (response != null) {
TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
if (!res.messages.isEmpty()) {
TLRPC.TL_messages_dialogs dialogs = new TLRPC.TL_messages_dialogs();
TLRPC.Message newMessage = res.messages.get(0);
TLRPC.TL_dialog newDialog = new TLRPC.TL_dialog();
newDialog.flags = dialog.flags;
newDialog.top_message = newMessage.id;
newDialog.last_message_date = newMessage.date;
newDialog.notify_settings = dialog.notify_settings;
newDialog.pts = dialog.pts;
newDialog.unread_count = dialog.unread_count;
newDialog.read_inbox_max_id = dialog.read_inbox_max_id;
newDialog.read_outbox_max_id = dialog.read_outbox_max_id;
newMessage.dialog_id = newDialog.id = dialog.id;
dialogs.users.addAll(res.users);
dialogs.chats.addAll(res.chats);
dialogs.dialogs.add(newDialog);
dialogs.messages.addAll(res.messages);
dialogs.count = 1;
processDialogsUpdate(dialogs, null);
//MessagesStorage.getInstance().putMessages(res.messages, true, true, false, MediaController.getInstance().getAutodownloadMask(), true);
} else {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
TLRPC.TL_dialog currentDialog = dialogs_dict.get(dialog.id);
if (currentDialog != null && currentDialog.top_message == 0) {
deleteDialog(dialog.id, 3);
}
}
});
}
}
if (newTaskId != 0) {
//MessagesStorage.getInstance().removePendingTask(newTaskId);
}
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
checkingLastMessagesDialogs.remove(lower_id);
}
});
}
});
}
public void processDialogsUpdate(final TLRPC.messages_Dialogs dialogsRes, ArrayList<TLRPC.EncryptedChat> encChats) {
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
final HashMap<Long, TLRPC.TL_dialog> new_dialogs_dict = new HashMap<>();
final HashMap<Long, MessageObject> new_dialogMessage = new HashMap<>();
final HashMap<Integer, TLRPC.User> usersDict = new HashMap<>();
final HashMap<Integer, TLRPC.Chat> chatsDict = new HashMap<>();
final HashMap<Long, Integer> dialogsToUpdate = new HashMap<>();
for (int a = 0; a < dialogsRes.users.size(); a++) {
TLRPC.User u = dialogsRes.users.get(a);
usersDict.put(u.id, u);
}
for (int a = 0; a < dialogsRes.chats.size(); a++) {
TLRPC.Chat c = dialogsRes.chats.get(a);
chatsDict.put(c.id, c);
}
for (int a = 0; a < dialogsRes.messages.size(); a++) {
TLRPC.Message message = dialogsRes.messages.get(a);
if (message.to_id.channel_id != 0) {
TLRPC.Chat chat = chatsDict.get(message.to_id.channel_id);
if (chat != null && chat.left) {
continue;
}
} else if (message.to_id.chat_id != 0) {
TLRPC.Chat chat = chatsDict.get(message.to_id.chat_id);
if (chat != null && chat.migrated_to != null) {
continue;
}
}
MessageObject messageObject = new MessageObject(message, usersDict, chatsDict, false);
new_dialogMessage.put(messageObject.getDialogId(), messageObject);
}
for (int a = 0; a < dialogsRes.dialogs.size(); a++) {
TLRPC.TL_dialog d = dialogsRes.dialogs.get(a);
if (d.id == 0) {
if (d.peer.user_id != 0) {
d.id = d.peer.user_id;
} else if (d.peer.chat_id != 0) {
d.id = -d.peer.chat_id;
} else if (d.peer.channel_id != 0) {
d.id = -d.peer.channel_id;
}
}
if (DialogObject.isChannel(d)) {
TLRPC.Chat chat = chatsDict.get(-(int) d.id);
if (chat != null && chat.left) {
continue;
}
} else if ((int) d.id < 0) {
TLRPC.Chat chat = chatsDict.get(-(int) d.id);
if (chat != null && chat.migrated_to != null) {
continue;
}
}
if (d.last_message_date == 0) {
MessageObject mess = new_dialogMessage.get(d.id);
if (mess != null) {
d.last_message_date = mess.messageOwner.date;
}
}
new_dialogs_dict.put(d.id, d);
dialogsToUpdate.put(d.id, d.unread_count);
Integer value = dialogs_read_inbox_max.get(d.id);
if (value == null) {
value = 0;
}
dialogs_read_inbox_max.put(d.id, Math.max(value, d.read_inbox_max_id));
value = dialogs_read_outbox_max.get(d.id);
if (value == null) {
value = 0;
}
dialogs_read_outbox_max.put(d.id, Math.max(value, d.read_outbox_max_id));
}
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
putUsers(dialogsRes.users, true);
putChats(dialogsRes.chats, true);
for (HashMap.Entry<Long, TLRPC.TL_dialog> pair : new_dialogs_dict.entrySet()) {
Long key = pair.getKey();
TLRPC.TL_dialog value = pair.getValue();
TLRPC.TL_dialog currentDialog = dialogs_dict.get(key);
if (currentDialog == null) {
nextDialogsCacheOffset++;
dialogs_dict.put(key, value);
MessageObject messageObject = new_dialogMessage.get(value.id);
dialogMessage.put(key, messageObject);
if (messageObject != null && messageObject.messageOwner.to_id.channel_id == 0) {
dialogMessagesByIds.put(messageObject.getId(), messageObject);
if (messageObject.messageOwner.random_id != 0) {
dialogMessagesByRandomIds.put(messageObject.messageOwner.random_id, messageObject);
}
}
} else {
currentDialog.unread_count = value.unread_count;
MessageObject oldMsg = dialogMessage.get(key);
if (oldMsg == null || currentDialog.top_message > 0) {
if (oldMsg != null && oldMsg.deleted || value.top_message > currentDialog.top_message) {
dialogs_dict.put(key, value);
MessageObject messageObject = new_dialogMessage.get(value.id);
dialogMessage.put(key, messageObject);
if (messageObject != null && messageObject.messageOwner.to_id.channel_id == 0) {
dialogMessagesByIds.put(messageObject.getId(), messageObject);
if (messageObject.messageOwner.random_id != 0) {
dialogMessagesByRandomIds.put(messageObject.messageOwner.random_id, messageObject);
}
}
if (oldMsg != null) {
dialogMessagesByIds.remove(oldMsg.getId());
if (oldMsg.messageOwner.random_id != 0) {
dialogMessagesByRandomIds.remove(oldMsg.messageOwner.random_id);
}
}
if (messageObject == null) {
checkLastDialogMessage(value, null, 0);
}
}
} else {
MessageObject newMsg = new_dialogMessage.get(value.id);
if (oldMsg.deleted || newMsg == null || newMsg.messageOwner.date > oldMsg.messageOwner.date) {
dialogs_dict.put(key, value);
dialogMessage.put(key, newMsg);
if (newMsg != null && newMsg.messageOwner.to_id.channel_id == 0) {
dialogMessagesByIds.put(newMsg.getId(), newMsg);
if (newMsg.messageOwner.random_id != 0) {
dialogMessagesByRandomIds.put(newMsg.messageOwner.random_id, newMsg);
}
}
dialogMessagesByIds.remove(oldMsg.getId());
if (oldMsg.messageOwner.random_id != 0) {
dialogMessagesByRandomIds.remove(oldMsg.messageOwner.random_id);
}
}
}
}
}
dialogs.clear();
dialogs.addAll(dialogs_dict.values());
sortDialogs(null);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);
}
});
}
});
}
public void markMessageContentAsRead(final MessageObject messageObject) {
}
@@ -1631,20 +1059,18 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
req.users.add(getInputUser(user));
}
return ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
return 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, final TLRPC.TL_error error) {
if (error != null) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
/* EDIT BY MR
if (error.text.startsWith("FLOOD_WAIT")) {
AlertsCreator.showFloodWaitAlert(error.text, fragment);
} else {
AlertsCreator.showAddUserAlert(error.text, fragment, false);
}
*/
NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidFailCreate);
}
});
@@ -1665,7 +1091,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors);
}, ConnectionsManager.RequestFlagFailOnServerErrors); */
}
return 0;
}
@@ -1693,7 +1119,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
request = req;
}
ConnectionsManager.getInstance().sendRequest(request, new RequestDelegate() {
/*ConnectionsManager.getInstance().sendRequest(request, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error != null) {
@@ -1701,40 +1127,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
processUpdates((TLRPC.Updates) response, false);
}
}, ConnectionsManager.RequestFlagInvokeAfter);
}, ConnectionsManager.RequestFlagInvokeAfter);*/
}
public long getUpdatesStartTime(int type) {
if (type == 0) {
return updatesStartWaitTimeSeq;
} else if (type == 1) {
return updatesStartWaitTimePts;
} else if (type == 2) {
return updatesStartWaitTimeQts;
}
return 0;
}
public void getDifference() {
}
private int getUpdateType(TLRPC.Update update) {
if (update instanceof TLRPC.TL_updateNewMessage || update instanceof TLRPC.TL_updateReadMessagesContents || update instanceof TLRPC.TL_updateReadHistoryInbox ||
update instanceof TLRPC.TL_updateReadHistoryOutbox || update instanceof TLRPC.TL_updateDeleteMessages || update instanceof TLRPC.TL_updateWebPage ||
update instanceof TLRPC.TL_updateEditMessage) {
return 0;
/*} else if (update instanceof TLRPC.TL_updateNewEncryptedMessage) {
return 1;
} else if (update instanceof TLRPC.TL_updateNewChannelMessage || update instanceof TLRPC.TL_updateDeleteChannelMessages || update instanceof TLRPC.TL_updateEditChannelMessage) {
return 2;*/
} else {
return 3;
}
}
public void processUpdates(final TLRPC.Updates updates, boolean fromQueue) {
}
public boolean isDialogMuted(long dialog_id) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
int mute_type = preferences.getInt("notify2_" + dialog_id, 0);
@@ -1960,7 +1355,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
TLRPC.TL_contacts_resolveUsername req = new TLRPC.TL_contacts_resolveUsername();
req.username = username;
final int reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
final int reqId = 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@@ -1984,19 +1379,18 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
} else {
if (fragment != null && fragment.getParentActivity() != null) {
/*
try {
Toast.makeText(fragment.getParentActivity(), LocaleController.getString("NoUsernameFound", R.string.NoUsernameFound), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
*/
}
}
}
});
}
});
*/
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
@@ -26,7 +26,6 @@
******************************************************************************/
// EDIT BY MR
package org.telegram.messenger;
@@ -317,5 +316,7 @@ public class MrMailbox {
public final static int MR_TITLE_USERNAME = 2;
public final static int MR_TITLE_SELF = 3;
// some rest of Telegram ...
public native static long getCurrentTimeMillis ();
public native static int getCurrentTime ();
}
// /EDIT BY MR
@@ -34,11 +34,8 @@ import android.os.Message;
import android.os.Process;
import android.os.SystemClock;
import android.service.media.MediaBrowserService;
import android.text.TextUtils;
import org.telegram.messenger.audioinfo.AudioInfo;
import org.telegram.messenger.query.SharedMediaQuery;
import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.LaunchActivity;
@@ -47,7 +44,6 @@ import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class MusicBrowserService extends MediaBrowserService implements NotificationCenter.NotificationCenterDelegate {
@@ -356,7 +356,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
String finalPath = (String) args[1];
long finalSize = (Long) args[2];
boolean isEncrypted = ((int) messageObject.getDialogId()) == 0;
FileLoader.getInstance().checkUploadNewDataAvailable(finalPath, isEncrypted, finalSize);
//FileLoader.getInstance().checkUploadNewDataAvailable(finalPath, isEncrypted, finalSize);
if (finalSize != 0) {
/*
ArrayList<DelayedMessage> arr = delayedMessages.get(messageObject.messageOwner.attachPath);
@@ -52,12 +52,14 @@ public class Utilities {
public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer);
public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin);
public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap);
private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
//private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
public native static String readlink(String path);
/*
public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {
aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length);
}
*/
public static Integer parseInt(String value) {
if (value == null) {
@@ -18,7 +18,6 @@ import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.Utilities;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
@@ -119,7 +119,7 @@ public class MessagesSearchQuery {
req.limit = 1;
req.q = query;
req.filter = new TLRPC.TL_inputMessagesFilterEmpty();
mergeReqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
mergeReqId = 0;/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@@ -137,7 +137,7 @@ public class MessagesSearchQuery {
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors);
}, ConnectionsManager.RequestFlagFailOnServerErrors);*/
return;
} else {
lastMergeDialogId = 0;
@@ -157,7 +157,7 @@ public class MessagesSearchQuery {
final int currentReqId = ++lastReqId;
lastSearchQuery = query;
final long queryWithDialogFinal = queryWithDialog;
reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
reqId = 0; /* ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@@ -202,7 +202,7 @@ public class MessagesSearchQuery {
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors);
}, ConnectionsManager.RequestFlagFailOnServerErrors);*/
}
public static String getLastSearchQuery() {
@@ -122,6 +122,7 @@ public class SearchQuery {
loaded = true;
} else {
loading = true;
/*
TLRPC.TL_contacts_getTopPeers req = new TLRPC.TL_contacts_getTopPeers();
req.hash = 0;
req.bots_pm = false;
@@ -152,7 +153,6 @@ public class SearchQuery {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.reloadHints);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.reloadInlineHints);
final HashMap<Integer, Integer> inlineDatesCopy = new HashMap<>(inlineDates);
/*
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
@@ -205,12 +205,11 @@ public class SearchQuery {
}
}
});
*/
}
});
}
}
});
});*/
}
}
@@ -261,7 +260,7 @@ public class SearchQuery {
for (int a = 0; a < inlineBots.size(); a++) {
if (inlineBots.get(a).peer.user_id == uid) {
inlineBots.remove(a);
TLRPC.TL_contacts_resetTopPeerRating req = new TLRPC.TL_contacts_resetTopPeerRating();
/*TLRPC.TL_contacts_resetTopPeerRating req = new TLRPC.TL_contacts_resetTopPeerRating();
req.category = new TLRPC.TL_topPeerCategoryBotsInline();
req.peer = MessagesController.getInputPeer(uid);
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@@ -271,6 +270,7 @@ public class SearchQuery {
}
});
deletePeer(uid, 1);
*/
NotificationCenter.getInstance().postNotificationName(NotificationCenter.reloadInlineHints);
return;
}
@@ -283,7 +283,7 @@ public class SearchQuery {
if (hints.get(a).peer.user_id == uid) {
hints.remove(a);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.reloadHints);
TLRPC.TL_contacts_resetTopPeerRating req = new TLRPC.TL_contacts_resetTopPeerRating();
/*TLRPC.TL_contacts_resetTopPeerRating req = new TLRPC.TL_contacts_resetTopPeerRating();
req.category = new TLRPC.TL_topPeerCategoryCorrespondents();
req.peer = MessagesController.getInputPeer(uid);
deletePeer(uid, 0);
@@ -292,7 +292,7 @@ public class SearchQuery {
public void run(TLObject response, TLRPC.TL_error error) {
}
});
});*/
return;
}
}
@@ -400,19 +400,4 @@ public class SearchQuery {
});
*/
}
private static void deletePeer(final int did, final int type) {
/*
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
try {
MessagesStorage.getInstance().getDatabase().executeFast(String.format(Locale.US, "DELETE FROM chat_hints WHERE did = %d AND type = %d", did, type)).stepThis().dispose();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
*/
}
}
@@ -8,9 +8,6 @@
package org.telegram.messenger.query;
import android.text.TextUtils;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ImageLoader;
@@ -18,17 +15,12 @@ import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MrMailbox;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.Utilities;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
public class SharedMediaQuery {
@@ -66,7 +58,7 @@ public class SharedMediaQuery {
if (req.peer == null) {
return;
}
int reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
int reqId = 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
@@ -81,7 +73,7 @@ public class SharedMediaQuery {
processLoadedMedia(res, uid, offset, count, max_id, type, false, classGuid, isChannel, topReached);
}
}
});
});*/
ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);
}
}
@@ -17,7 +17,6 @@ import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
@@ -205,7 +204,7 @@ public class StickersQuery {
});
*/
} else {
final TLRPC.TL_messages_getAllStickers req = new TLRPC.TL_messages_getAllStickers();
/*final TLRPC.TL_messages_getAllStickers req = new TLRPC.TL_messages_getAllStickers();
req.hash = force ? 0 : loadHash;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
@@ -266,7 +265,7 @@ public class StickersQuery {
}
});
}
});
});*/
}
}
@@ -477,7 +476,7 @@ public class StickersQuery {
loadHash = calcStickersHash(stickerSets);
putStickersToCache(stickerSets, loadDate, loadHash);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.stickersDidLoaded);
TLRPC.TL_messages_installStickerSet req = new TLRPC.TL_messages_installStickerSet();
/*TLRPC.TL_messages_installStickerSet req = new TLRPC.TL_messages_installStickerSet();
req.stickerset = stickerSetID;
req.disabled = hide == 1;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@@ -490,9 +489,9 @@ public class StickersQuery {
}
}, 1000);
}
});
});*/
} else {
TLRPC.TL_messages_uninstallStickerSet req = new TLRPC.TL_messages_uninstallStickerSet();
/*TLRPC.TL_messages_uninstallStickerSet req = new TLRPC.TL_messages_uninstallStickerSet();
req.stickerset = stickerSetID;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
@@ -513,7 +512,7 @@ public class StickersQuery {
}
});
}
});
});*/
}
}
}
@@ -8,24 +8,14 @@ public abstract class AbstractSerializedData {
public abstract void writeBool(boolean value);
public abstract void writeBytes(byte[] b);
public abstract void writeBytes(byte[] b, int offset, int count);
public abstract void writeByte(int i);
public abstract void writeByte(byte b);
public abstract void writeString(String s);
public abstract void writeByteArray(byte[] b, int offset, int count);
public abstract void writeByteArray(byte[] b);
public abstract void writeDouble(double d);
public abstract void writeByteBuffer(NativeByteBuffer buffer);
public abstract int readInt32(boolean exception);
public abstract boolean readBool(boolean exception);
@@ -40,8 +30,6 @@ public abstract class AbstractSerializedData {
public abstract byte[] readByteArray(boolean exception);
public abstract NativeByteBuffer readByteBuffer(boolean exception);
public abstract double readDouble(boolean exception);
public abstract int length();
@@ -15,10 +15,8 @@ import org.telegram.messenger.BuildVars;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MrMailbox;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import java.net.Inet4Address;
import java.net.Inet6Address;
@@ -27,38 +25,21 @@ import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class ConnectionsManager {
public final static int ConnectionTypeGeneric = 1;
public final static int ConnectionTypeDownload = 2;
public final static int ConnectionTypeUpload = 4;
public final static int ConnectionTypePush = 8;
public final static int ConnectionTypeDownload2 = ConnectionTypeDownload | (1 << 16);
public final static int RequestFlagEnableUnauthorized = 1;
public final static int RequestFlagFailOnServerErrors = 2;
public final static int RequestFlagCanCompress = 4;
public final static int RequestFlagWithoutLogin = 8;
public final static int RequestFlagTryDifferentDc = 16;
public final static int RequestFlagForceDownload = 32;
public final static int RequestFlagInvokeAfter = 64;
public final static int RequestFlagNeedQuickAck = 128;
public final static int ConnectionStateConnecting = 1;
public final static int ConnectionStateWaitingForNetwork = 2;
public final static int ConnectionStateConnected = 3;
public final static int ConnectionStateUpdating = 4;
public final static int DEFAULT_DATACENTER_ID = Integer.MAX_VALUE;
private long lastPauseTime = System.currentTimeMillis();
private boolean appPaused = true;
private int lastClassGuid = 1;
private boolean isUpdating = false;
private int connectionState = native_getConnectionState();
private AtomicInteger lastRequestToken = new AtomicInteger(1);
//private int connectionState = native_getConnectionState();
private PowerManager.WakeLock wakeLock = null;
private static volatile ConnectionsManager Instance = null;
@@ -87,17 +68,14 @@ public class ConnectionsManager {
}
public long getCurrentTimeMillis() {
return native_getCurrentTimeMillis();
return MrMailbox.getCurrentTimeMillis();
}
public int getCurrentTime() {
return native_getCurrentTime();
}
public int getTimeDifference() {
return native_getTimeDifference();
return MrMailbox.getCurrentTime();
}
/*
public int sendRequest(TLObject object, RequestDelegate completionBlock) {
return sendRequest(object, completionBlock, null, 0);
}
@@ -115,78 +93,24 @@ public class ConnectionsManager {
}
public int sendRequest(final TLObject object, final RequestDelegate onComplete, final QuickAckDelegate onQuickAck, final int flags, final int datacenterId, final int connetionType, final boolean immediate) {
return 0; // EDIT BY MR
/* EDIT BY MR
final int requestToken = lastRequestToken.getAndIncrement();
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
FileLog.d("tmessages", "send request " + object + " with token = " + requestToken);
try {
NativeByteBuffer buffer = new NativeByteBuffer(object.getObjectSize());
object.serializeToStream(buffer);
object.freeResources();
native_sendRequest(buffer.address, new RequestDelegateInternal() {
@Override
public void run(int response, int errorCode, String errorText) {
try {
TLObject resp = null;
TLRPC.TL_error error = null;
if (response != 0) {
NativeByteBuffer buff = NativeByteBuffer.wrap(response);
buff.reused = true;
resp = object.deserializeResponse(buff, buff.readInt32(true), true);
} else if (errorText != null) {
error = new TLRPC.TL_error();
error.code = errorCode;
error.text = errorText;
FileLog.e("tmessages", object + " got error " + error.code + " " + error.text);
}
FileLog.d("tmessages", "java received " + resp + " error = " + error);
final TLObject finalResponse = resp;
final TLRPC.TL_error finalError = error;
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
onComplete.run(finalResponse, finalError);
if (finalResponse != null) {
finalResponse.freeResources();
}
}
});
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}, onQuickAck, flags, datacenterId, connetionType, immediate, requestToken);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
return requestToken;
*/
return 0; // this is the old Telegram function to send a request, no longer needed
}
*/
public void cancelRequest(int token, boolean notifyServer) {
native_cancelRequest(token, notifyServer);
//native_cancelRequest(token, notifyServer);
}
public void cleanup() {
native_cleanUp();
//native_cleanUp();
}
public void cancelRequestsForGuid(int guid) {
native_cancelRequestsForGuid(guid);
//native_cancelRequestsForGuid(guid);
}
public void bindRequestToGuid(int requestToken, int guid) {
native_bindRequestToGuid(requestToken, guid);
}
public void applyDatacenterAddress(int datacenterId, String ipAddress, int port) {
native_applyDatacenterAddress(datacenterId, ipAddress, port);
//native_bindRequestToGuid(requestToken, guid);
}
public int getConnectionState() {
@@ -200,20 +124,20 @@ public class ConnectionsManager {
}
public void setUserId(int id) {
native_setUserId(id);
//native_setUserId(id);
}
private void checkConnection() {
native_setUseIpv6(useIpv6Address());
native_setNetworkAvailable(isNetworkOnline());
//native_setUseIpv6(useIpv6Address());
//native_setNetworkAvailable(isNetworkOnline());
}
public void setPushConnectionEnabled(boolean value) {
native_setPushConnectionEnabled(value);
//native_setPushConnectionEnabled(value);
}
public void init(int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String configPath, String logPath, int userId, boolean enablePushConnection) {
native_init(version, layer, apiId, deviceModel, systemVersion, appVersion, langCode, configPath, logPath, userId, enablePushConnection);
//native_init(version, layer, apiId, deviceModel, systemVersion, appVersion, langCode, configPath, logPath, userId, enablePushConnection);
checkConnection();
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
@Override
@@ -226,19 +150,11 @@ public class ConnectionsManager {
}
public void switchBackend() {
native_switchBackend();
//native_switchBackend();
}
public void resumeNetworkMaybe() {
native_resumeNetwork(true);
}
public void updateDcSettings() {
native_updateDcSettings();
}
public long getPauseTime() {
return lastPauseTime;
//native_resumeNetwork(true);
}
public void setAppPaused(final boolean value, final boolean byScreenState) {
@@ -250,7 +166,7 @@ public class ConnectionsManager {
if (lastPauseTime == 0) {
lastPauseTime = System.currentTimeMillis();
}
native_pauseNetwork();
//native_pauseNetwork();
} else {
if (appPaused) {
return;
@@ -260,135 +176,10 @@ public class ConnectionsManager {
ContactsController.getInstance().checkContacts();
}
lastPauseTime = 0;
native_resumeNetwork(false);
//native_resumeNetwork(false);
}
}
public static void onUnparsedMessageReceived(int address) {
try {
NativeByteBuffer buff = NativeByteBuffer.wrap(address);
buff.reused = true;
final TLObject message = TLClassStore.Instance().TLdeserialize(buff, buff.readInt32(true), true);
if (message instanceof TLRPC.Updates) {
FileLog.d("tmessages", "java received " + message);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (getInstance().wakeLock.isHeld()) {
FileLog.d("tmessages", "release wakelock");
getInstance().wakeLock.release();
}
}
});
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
MessagesController.getInstance().processUpdates((TLRPC.Updates) message, false);
}
});
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
public static void onUpdate() {
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
MessagesController.getInstance().updateTimerProc();
}
});
}
public static void onSessionCreated() {
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
MessagesController.getInstance().getDifference();
}
});
}
public static void onConnectionStateChanged(final int state) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
getInstance().connectionState = state;
NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState);
}
});
}
public static void onLogout() {
/*
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (UserConfig.getClientUserId() != 0) {
UserConfig.clearConfig();
MessagesController.getInstance().performLogout(false);
}
}
});
*/
}
public static void onUpdateConfig(int address) {
try {
NativeByteBuffer buff = NativeByteBuffer.wrap(address);
buff.reused = true;
final TLRPC.TL_config message = TLRPC.TL_config.TLdeserialize(buff, buff.readInt32(true), true);
if (message != null) {
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
MessagesController.getInstance().updateConfig(message);
}
});
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
public static void onInternalPushReceived() {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
try {
if (!getInstance().wakeLock.isHeld()) {
getInstance().wakeLock.acquire(10000);
FileLog.d("tmessages", "acquire wakelock");
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
public static native void native_switchBackend();
public static native void native_pauseNetwork();
public static native void native_setUseIpv6(boolean value);
public static native void native_updateDcSettings();
public static native void native_setNetworkAvailable(boolean value);
public static native void native_resumeNetwork(boolean partial);
public static native long native_getCurrentTimeMillis();
public static native int native_getCurrentTime();
public static native int native_getTimeDifference();
public static native void native_sendRequest(int object, RequestDelegateInternal onComplete, QuickAckDelegate onQuickAck, int flags, int datacenterId, int connetionType, boolean immediate, int requestToken);
public static native void native_cancelRequest(int token, boolean notifyServer);
public static native void native_cleanUp();
public static native void native_cancelRequestsForGuid(int guid);
public static native void native_bindRequestToGuid(int requestToken, int guid);
public static native void native_applyDatacenterAddress(int datacenterId, String ipAddress, int port);
public static native int native_getConnectionState();
public static native void native_setUserId(int id);
public static native void native_init(int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String configPath, String logPath, int userId, boolean enablePushConnection);
public static native void native_setJava(boolean useJavaByteBuffers);
public static native void native_setPushConnectionEnabled(boolean value);
public int generateClassGuid() {
return lastClassGuid++;
}
@@ -419,25 +210,6 @@ public class ConnectionsManager {
return false;
}
public void applyCountryPortNumber(String number) {
}
public void setIsUpdating(final boolean value) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (isUpdating == value) {
return;
}
isUpdating = value;
if (connectionState == ConnectionStateConnected) {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState);
}
}
});
}
@SuppressLint("NewApi")
protected static boolean useIpv6Address() {
if (Build.VERSION.SDK_INT < 19) {
@@ -1,510 +0,0 @@
package org.telegram.tgnet;
import org.telegram.messenger.FileLog;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class NativeByteBuffer extends AbstractSerializedData {
protected int address;
public ByteBuffer buffer;
private boolean justCalc;
private int len;
public boolean reused = true;
private static final ThreadLocal<NativeByteBuffer> addressWrapper = new ThreadLocal<NativeByteBuffer>() {
@Override
protected NativeByteBuffer initialValue() {
return new NativeByteBuffer(0, true);
}
};
public static NativeByteBuffer wrap(int address) {
NativeByteBuffer result = addressWrapper.get();
if (address != 0) {
if (!result.reused) {
FileLog.e("tmessages", "forgot to reuse?");
}
result.address = address;
result.reused = false;
result.buffer = native_getJavaByteBuffer(address);
result.buffer.limit(native_limit(address));
int position = native_position(address);
if (position <= result.buffer.limit()) {
result.buffer.position(position);
}
result.buffer.order(ByteOrder.LITTLE_ENDIAN);
}
return result;
}
private NativeByteBuffer(int address, boolean wrap) {
}
public NativeByteBuffer(int size) throws Exception {
if (size >= 0) {
address = native_getFreeBuffer(size);
if (address != 0) {
buffer = native_getJavaByteBuffer(address);
buffer.position(0);
buffer.limit(size);
buffer.order(ByteOrder.LITTLE_ENDIAN);
}
} else {
throw new Exception("invalid NativeByteBuffer size");
}
}
public NativeByteBuffer(boolean calculate) {
justCalc = calculate;
}
public int position() {
return buffer.position();
}
public void position(int position) {
buffer.position(position);
}
public int capacity() {
return buffer.capacity();
}
public int limit() {
return buffer.limit();
}
public void limit(int limit) {
buffer.limit(limit);
}
public void put(ByteBuffer buff) {
buffer.put(buff);
}
public void rewind() {
if (justCalc) {
len = 0;
} else {
buffer.rewind();
}
}
public void compact() {
buffer.compact();
}
public boolean hasRemaining() {
return buffer.hasRemaining();
}
public void writeInt32(int x) {
try {
if (!justCalc) {
buffer.putInt(x);
} else {
len += 4;
}
} catch(Exception e) {
FileLog.e("tmessages", "write int32 error");
}
}
public void writeInt64(long x) {
try {
if (!justCalc) {
buffer.putLong(x);
} else {
len += 8;
}
} catch(Exception e) {
FileLog.e("tmessages", "write int64 error");
}
}
public void writeBool(boolean value) {
if (!justCalc) {
if (value) {
writeInt32(0x997275b5);
} else {
writeInt32(0xbc799737);
}
} else {
len += 4;
}
}
public void writeBytes(byte[] b) {
try {
if (!justCalc) {
buffer.put(b);
} else {
len += b.length;
}
} catch (Exception e) {
FileLog.e("tmessages", "write raw error");
}
}
public void writeBytes(byte[] b, int offset, int count) {
try {
if (!justCalc) {
buffer.put(b, offset, count);
} else {
len += count;
}
} catch (Exception e) {
FileLog.e("tmessages", "write raw error");
}
}
public void writeByte(int i) {
writeByte((byte) i);
}
public void writeByte(byte b) {
try {
if (!justCalc) {
buffer.put(b);
} else {
len += 1;
}
} catch (Exception e) {
FileLog.e("tmessages", "write byte error");
}
}
public void writeString(String s) {
try {
writeByteArray(s.getBytes("UTF-8"));
} catch(Exception e) {
FileLog.e("tmessages", "write string error");
}
}
public void writeByteArray(byte[] b, int offset, int count) {
try {
if(count <= 253) {
if (!justCalc) {
buffer.put((byte)count);
} else {
len += 1;
}
} else {
if (!justCalc) {
buffer.put((byte)254);
buffer.put((byte)count);
buffer.put((byte)(count >> 8));
buffer.put((byte)(count >> 16));
} else {
len += 4;
}
}
if (!justCalc) {
buffer.put(b, offset, count);
} else {
len += count;
}
int i = count <= 253 ? 1 : 4;
while ((count + i) % 4 != 0) {
if (!justCalc) {
buffer.put((byte)0);
} else {
len += 1;
}
i++;
}
} catch (Exception e) {
FileLog.e("tmessages", "write byte array error");
}
}
public void writeByteArray(byte[] b) {
try {
if (b.length <= 253) {
if (!justCalc) {
buffer.put((byte) b.length);
} else {
len += 1;
}
} else {
if (!justCalc) {
buffer.put((byte) 254);
buffer.put((byte) b.length);
buffer.put((byte) (b.length >> 8));
buffer.put((byte) (b.length >> 16));
} else {
len += 4;
}
}
if (!justCalc) {
buffer.put(b);
} else {
len += b.length;
}
int i = b.length <= 253 ? 1 : 4;
while((b.length + i) % 4 != 0) {
if (!justCalc) {
buffer.put((byte) 0);
} else {
len += 1;
}
i++;
}
} catch (Exception e) {
FileLog.e("tmessages", "write byte array error");
}
}
public void writeDouble(double d) {
try {
writeInt64(Double.doubleToRawLongBits(d));
} catch(Exception e) {
FileLog.e("tmessages", "write double error");
}
}
public void writeByteBuffer(NativeByteBuffer b) {
try {
int l = b.limit();
if (l <= 253) {
if (!justCalc) {
buffer.put((byte) l);
} else {
len += 1;
}
} else {
if (!justCalc) {
buffer.put((byte) 254);
buffer.put((byte) l);
buffer.put((byte) (l >> 8));
buffer.put((byte) (l >> 16));
} else {
len += 4;
}
}
if (!justCalc) {
b.rewind();
buffer.put(b.buffer);
} else {
len += l;
}
int i = l <= 253 ? 1 : 4;
while((l + i) % 4 != 0) {
if (!justCalc) {
buffer.put((byte) 0);
} else {
len += 1;
}
i++;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
public void writeBytes(NativeByteBuffer b) {
if (justCalc) {
len += b.limit();
} else {
b.rewind();
buffer.put(b.buffer);
}
}
public int getIntFromByte(byte b) {
return b >= 0 ? b : ((int)b) + 256;
}
public int length() {
if (!justCalc) {
return buffer.position();
}
return len;
}
public void skip(int count) {
if (count == 0) {
return;
}
if (!justCalc) {
buffer.position(buffer.position() + count);
} else {
len += count;
}
}
public int getPosition() {
return buffer.position();
}
public int readInt32(boolean exception) {
try {
return buffer.getInt();
} catch (Exception e) {
if (exception) {
throw new RuntimeException("read int32 error", e);
} else {
FileLog.e("tmessages", "read int32 error");
}
}
return 0;
}
public boolean readBool(boolean exception) {
int consructor = readInt32(exception);
if (consructor == 0x997275b5) {
return true;
} else if (consructor == 0xbc799737) {
return false;
}
if (exception) {
throw new RuntimeException("Not bool value!");
} else {
FileLog.e("tmessages", "Not bool value!");
}
return false;
}
public long readInt64(boolean exception) {
try {
return buffer.getLong();
} catch (Exception e) {
if (exception) {
throw new RuntimeException("read int64 error", e);
} else {
FileLog.e("tmessages", "read int64 error");
}
}
return 0;
}
public void readBytes(byte[] b, boolean exception) {
try {
buffer.get(b);
} catch (Exception e) {
if (exception) {
throw new RuntimeException("read raw error", e);
} else {
FileLog.e("tmessages", "read raw error");
}
}
}
public byte[] readData(int count, boolean exception) {
byte[] arr = new byte[count];
readBytes(arr, exception);
return arr;
}
public String readString(boolean exception) {
try {
int sl = 1;
int l = getIntFromByte(buffer.get());
if(l >= 254) {
l = getIntFromByte(buffer.get()) | (getIntFromByte(buffer.get()) << 8) | (getIntFromByte(buffer.get()) << 16);
sl = 4;
}
byte[] b = new byte[l];
buffer.get(b);
int i = sl;
while((l + i) % 4 != 0) {
buffer.get();
i++;
}
return new String(b, "UTF-8");
} catch (Exception e) {
if (exception) {
throw new RuntimeException("read string error", e);
} else {
FileLog.e("tmessages", "read string error");
}
}
return null;
}
public byte[] readByteArray(boolean exception) {
try {
int sl = 1;
int l = getIntFromByte(buffer.get());
if (l >= 254) {
l = getIntFromByte(buffer.get()) | (getIntFromByte(buffer.get()) << 8) | (getIntFromByte(buffer.get()) << 16);
sl = 4;
}
byte[] b = new byte[l];
buffer.get(b);
int i = sl;
while((l + i) % 4 != 0) {
buffer.get();
i++;
}
return b;
} catch (Exception e) {
if (exception) {
throw new RuntimeException("read byte array error", e);
} else {
FileLog.e("tmessages", "read byte array error");
}
}
return null;
}
public NativeByteBuffer readByteBuffer(boolean exception) {
try {
int sl = 1;
int l = getIntFromByte(buffer.get());
if (l >= 254) {
l = getIntFromByte(buffer.get()) | (getIntFromByte(buffer.get()) << 8) | (getIntFromByte(buffer.get()) << 16);
sl = 4;
}
NativeByteBuffer b = new NativeByteBuffer(l);
int old = buffer.limit();
buffer.limit(buffer.position() + l);
b.buffer.put(buffer);
buffer.limit(old);
b.buffer.position(0);
int i = sl;
while((l + i) % 4 != 0) {
buffer.get();
i++;
}
return b;
} catch (Exception e) {
if (exception) {
throw new RuntimeException("read byte array error", e);
} else {
FileLog.e("tmessages", "read byte array error");
}
}
return null;
}
public double readDouble(boolean exception) {
try {
return Double.longBitsToDouble(readInt64(exception));
} catch(Exception e) {
if (exception) {
throw new RuntimeException("read double error", e);
} else {
FileLog.e("tmessages", "read double error");
}
}
return 0;
}
public void reuse() {
if (address != 0) {
reused = true;
native_reuse(address);
}
}
public static native int native_getFreeBuffer(int length);
public static native ByteBuffer native_getJavaByteBuffer(int address);
public static native int native_limit(int address);
public static native int native_position(int address);
public static native void native_reuse(int address);
}
@@ -464,14 +464,4 @@ public class SerializedData extends AbstractSerializedData {
}
return 0;
}
@Override
public void writeByteBuffer(NativeByteBuffer buffer) {
}
@Override
public NativeByteBuffer readByteBuffer(boolean exception) {
return null;
}
}
@@ -1,67 +0,0 @@
/*
* This is the source code of Telegram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package org.telegram.tgnet;
import org.telegram.messenger.FileLog;
import java.util.HashMap;
public class TLClassStore {
private HashMap<Integer, Class> classStore;
public TLClassStore() {
classStore = new HashMap<>();
classStore.put(TLRPC.TL_error.constructor, TLRPC.TL_error.class);
classStore.put(TLRPC.TL_decryptedMessageService.constructor, TLRPC.TL_decryptedMessageService.class);
classStore.put(TLRPC.TL_decryptedMessage.constructor, TLRPC.TL_decryptedMessage.class);
classStore.put(TLRPC.TL_config.constructor, TLRPC.TL_config.class);
classStore.put(TLRPC.TL_decryptedMessageLayer.constructor, TLRPC.TL_decryptedMessageLayer.class);
classStore.put(TLRPC.TL_decryptedMessage_layer17.constructor, TLRPC.TL_decryptedMessage.class);
classStore.put(TLRPC.TL_decryptedMessageService_layer8.constructor, TLRPC.TL_decryptedMessageService_layer8.class);
classStore.put(TLRPC.TL_decryptedMessage_layer8.constructor, TLRPC.TL_decryptedMessage_layer8.class);
classStore.put(TLRPC.TL_message_secret.constructor, TLRPC.TL_message_secret.class);
classStore.put(TLRPC.TL_message_secret_old.constructor, TLRPC.TL_message_secret_old.class);
classStore.put(TLRPC.TL_messageEncryptedAction.constructor, TLRPC.TL_messageEncryptedAction.class);
classStore.put(TLRPC.TL_null.constructor, TLRPC.TL_null.class);
classStore.put(TLRPC.TL_updateShortChatMessage.constructor, TLRPC.TL_updateShortChatMessage.class);
classStore.put(TLRPC.TL_updates.constructor, TLRPC.TL_updates.class);
classStore.put(TLRPC.TL_updateShortMessage.constructor, TLRPC.TL_updateShortMessage.class);
classStore.put(TLRPC.TL_updateShort.constructor, TLRPC.TL_updateShort.class);
classStore.put(TLRPC.TL_updatesCombined.constructor, TLRPC.TL_updatesCombined.class);
classStore.put(TLRPC.TL_updateShortSentMessage.constructor, TLRPC.TL_updateShortSentMessage.class);
classStore.put(TLRPC.TL_updatesTooLong.constructor, TLRPC.TL_updatesTooLong.class);
}
static TLClassStore store = null;
public static TLClassStore Instance() {
if (store == null) {
store = new TLClassStore();
}
return store;
}
public TLObject TLdeserialize(NativeByteBuffer stream, int constructor, boolean exception) {
Class objClass = classStore.get(constructor);
if (objClass != null) {
TLObject response;
try {
response = (TLObject) objClass.newInstance();
} catch (Throwable e) {
FileLog.e("tmessages", e);
return null;
}
response.readParams(stream, exception);
return response;
}
return null;
}
}
@@ -10,13 +10,15 @@ package org.telegram.tgnet;
public class TLObject {
public boolean disableFree = false;
//public boolean disableFree = false;
/*
private static final ThreadLocal<NativeByteBuffer> sizeCalculator = new ThreadLocal<NativeByteBuffer>() {
@Override
protected NativeByteBuffer initialValue() {
return new NativeByteBuffer(true);
}
};
*/
public TLObject() {
@@ -30,18 +32,7 @@ public class TLObject {
}
public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) {
return null;
}
public void freeResources() {
}
public int getObjectSize() {
NativeByteBuffer byteBuffer = sizeCalculator.get();
byteBuffer.rewind();
serializeToStream(sizeCalculator.get());
return byteBuffer.length();
return 0;
}
}
File diff suppressed because it is too large Load Diff
@@ -49,11 +49,12 @@ public class BaseSearchAdapter extends BaseFragmentAdapter {
notifyDataSetChanged();
return;
}
TLRPC.TL_contacts_search req = new TLRPC.TL_contacts_search();
/*TLRPC.TL_contacts_search req = new TLRPC.TL_contacts_search();
req.q = query;
req.limit = 50;
final int currentReqId = ++lastReqId;
reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
req.limit = 50;*/
/*final int currentReqId =*/
++lastReqId;
reqId = 0; /* ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@@ -82,7 +83,7 @@ public class BaseSearchAdapter extends BaseFragmentAdapter {
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors);
}, ConnectionsManager.RequestFlagFailOnServerErrors);*/
}
/*
@@ -50,11 +50,11 @@ public abstract class BaseSearchAdapterRecycler extends RecyclerView.Adapter {
notifyDataSetChanged();
return;
}
TLRPC.TL_contacts_search req = new TLRPC.TL_contacts_search();
/*TLRPC.TL_contacts_search req = new TLRPC.TL_contacts_search();
req.q = query;
req.limit = 50;
final int currentReqId = ++lastReqId;
reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
req.limit = 50;*/
/*final int currentReqId =*/ ++lastReqId;
reqId = 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@@ -80,7 +80,7 @@ public abstract class BaseSearchAdapterRecycler extends RecyclerView.Adapter {
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors);
}, ConnectionsManager.RequestFlagFailOnServerErrors);*/
}
public void loadRecentHashtags() {
@@ -9,13 +9,11 @@
package org.telegram.ui.Adapters;
import android.content.Context;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessageObject;
@@ -26,8 +24,6 @@ import org.telegram.messenger.support.widget.RecyclerView;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.Cells.DialogCell;
@@ -39,13 +35,9 @@ import org.telegram.ui.Cells.ProfileSearchCell;
import org.telegram.ui.Components.RecyclerListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
public class DialogsSearchAdapter extends BaseSearchAdapterRecycler {
@@ -206,11 +198,11 @@ public class DialogsSearchAdapter extends BaseSearchAdapterRecycler {
req.offset_peer = new TLRPC.TL_inputPeerEmpty();
}
lastMessagesSearchString = query;
final int currentReqId = ++lastReqId;
/*final int currentReqId =*/ ++lastReqId;
if (delegate != null) {
delegate.searchStateChanged(true);
}
reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
reqId = 0;/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@@ -248,7 +240,7 @@ public class DialogsSearchAdapter extends BaseSearchAdapterRecycler {
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors);
}, ConnectionsManager.RequestFlagFailOnServerErrors);*/
}
public boolean hasRecentRearch() {
@@ -3122,13 +3122,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
textToCheck = charSequence;
}
/*
final TLRPC.TL_messages_getWebPagePreview req = new TLRPC.TL_messages_getWebPagePreview();
if (textToCheck instanceof String) {
req.message = (String) textToCheck;
} else {
req.message = textToCheck.toString();
}
linkSearchRequestId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
*/
linkSearchRequestId = 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@@ -3156,7 +3158,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
});
}
});
});*/
ConnectionsManager.getInstance().bindRequestToGuid(linkSearchRequestId, classGuid);
}
});
@@ -710,7 +710,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
@Override
public void onClick(DialogInterface dialogInterface, int i) {
recentImages.remove(searchImage);
TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif();
/*TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif();
req.id = new TLRPC.TL_inputDocument();
req.id.id = searchImage.document.id;
req.id.access_hash = searchImage.document.access_hash;
@@ -720,7 +720,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
public void run(TLObject response, TLRPC.TL_error error) {
}
});
});*/
//MessagesStorage.getInstance().removeWebRecent(searchImage);
if (gifsAdapter != null) {
gifsAdapter.notifyDataSetChanged();
@@ -1559,7 +1559,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
return;
}
loadingRecentGifs = true;
TLRPC.TL_messages_getSavedGifs req = new TLRPC.TL_messages_getSavedGifs();
/*TLRPC.TL_messages_getSavedGifs req = new TLRPC.TL_messages_getSavedGifs();
req.hash = calcGifsHash(recentImages);
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
@@ -1600,7 +1600,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
}
});
}
});
});*/
}
@SuppressWarnings("unchecked")
@@ -367,7 +367,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not
stickerSet = StickersQuery.getStickerSetById(inputStickerSet.id);
}
if (stickerSet == null) {
TLRPC.TL_messages_getStickerSet req = new TLRPC.TL_messages_getStickerSet();
/*TLRPC.TL_messages_getStickerSet req = new TLRPC.TL_messages_getStickerSet();
req.stickerset = inputStickerSet;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
@@ -387,7 +387,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not
}
});
}
});
});*/
}
NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded);
updateFields();
@@ -405,7 +405,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not
@Override
public void onClick(View v) {
dismiss();
TLRPC.TL_messages_installStickerSet req = new TLRPC.TL_messages_installStickerSet();
/*TLRPC.TL_messages_installStickerSet req = new TLRPC.TL_messages_installStickerSet();
req.stickerset = inputStickerSet;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
@@ -430,7 +430,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not
}
});
}
});
});*/
}
}, LocaleController.getString("AddStickers", R.string.AddStickers), Theme.STICKERS_SHEET_ADD_TEXT_COLOR, true);
} else {
@@ -1082,6 +1082,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
int requestId = 0;
if (username != null) {
/*
TLRPC.TL_contacts_resolveUsername req = new TLRPC.TL_contacts_resolveUsername();
req.username = username;
requestId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@@ -1102,7 +1103,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
MessagesController.getInstance().putChats(res.chats, false);
//MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, false, true);
/*if (botChat != null) {
if (botChat != null) {
final TLRPC.User user = !res.users.isEmpty() ? res.users.get(0) : null;
if (user == null || user.bot && user.bot_nochats) {
try {
@@ -1131,7 +1132,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
}
});
presentFragment(fragment);
} else */ {
} else {
long dialog_id;
boolean isBot = false;
Bundle args = new Bundle();
@@ -1161,24 +1162,22 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
}
}
} else {
/*
try {
Toast.makeText(LaunchActivity.this, LocaleController.getString("NoUsernameFound", R.string.NoUsernameFound), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
*/
}
}
}
});
}
});
}); */
} else if (group != null) {
if (state == 0) {
final TLRPC.TL_messages_checkChatInvite req = new TLRPC.TL_messages_checkChatInvite();
req.hash = group;
requestId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
requestId = 0; /* ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@@ -1236,10 +1235,11 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors);
}, ConnectionsManager.RequestFlagFailOnServerErrors); */
} else if (state == 1) {
TLRPC.TL_messages_importChatInvite req = new TLRPC.TL_messages_importChatInvite();
req.hash = group;
/*
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
@@ -1291,7 +1291,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors);
}, ConnectionsManager.RequestFlagFailOnServerErrors); */
}
} else if (sticker != null) {
if (!mainFragmentsStack.isEmpty()) {
@@ -1223,7 +1223,7 @@ public class LoginActivity extends BaseFragment {
wrongNumber.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
TLRPC.TL_auth_cancelCode req = new TLRPC.TL_auth_cancelCode();
/*TLRPC.TL_auth_cancelCode req = new TLRPC.TL_auth_cancelCode();
req.phone_number = requestPhone;
req.phone_code_hash = phoneHash;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@@ -1231,7 +1231,7 @@ public class LoginActivity extends BaseFragment {
public void run(TLObject response, TLRPC.TL_error error) {
}
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);*/
onBackPressed();
setPage(0, true, null, true);
}
@@ -1247,7 +1247,7 @@ public class LoginActivity extends BaseFragment {
nextPressed = true;
needShowProgress();
TLRPC.TL_auth_resendCode req = new TLRPC.TL_auth_resendCode();
/*TLRPC.TL_auth_resendCode req = new TLRPC.TL_auth_resendCode();
req.phone_number = requestPhone;
req.phone_code_hash = phoneHash;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@@ -1280,7 +1280,7 @@ public class LoginActivity extends BaseFragment {
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);*/
}
@Override
@@ -1463,7 +1463,7 @@ public class LoginActivity extends BaseFragment {
if (nextType == 4) {
timeText.setText(LocaleController.getString("Calling", R.string.Calling));
createCodeTimer();
TLRPC.TL_auth_resendCode req = new TLRPC.TL_auth_resendCode();
/*TLRPC.TL_auth_resendCode req = new TLRPC.TL_auth_resendCode();
req.phone_number = requestPhone;
req.phone_code_hash = phoneHash;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@@ -1478,7 +1478,7 @@ public class LoginActivity extends BaseFragment {
});
}
}
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);*/
} else if (nextType == 3) {
AndroidUtilities.setWaitingForSms(false);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveSmsCode);
@@ -1521,13 +1521,13 @@ public class LoginActivity extends BaseFragment {
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveCall);
}
waitingForEvent = false;
final TLRPC.TL_auth_signIn req = new TLRPC.TL_auth_signIn();
/*final TLRPC.TL_auth_signIn req = new TLRPC.TL_auth_signIn();
req.phone_number = requestPhone;
req.phone_code = codeField.getText().toString();
req.phone_code_hash = phoneHash;
req.phone_code_hash = phoneHash;*/
destroyTimer();
needShowProgress();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@@ -1626,7 +1626,7 @@ public class LoginActivity extends BaseFragment {
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);*/
}
@Override
@@ -1874,7 +1874,7 @@ public class LoginActivity extends BaseFragment {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
needShowProgress();
TLRPC.TL_account_deleteAccount req = new TLRPC.TL_account_deleteAccount();
/*TLRPC.TL_account_deleteAccount req = new TLRPC.TL_account_deleteAccount();
req.reason = "Forgot password";
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
@@ -1895,7 +1895,7 @@ public class LoginActivity extends BaseFragment {
}
});
}
}, ConnectionsManager.RequestFlagWithoutLogin | ConnectionsManager.RequestFlagFailOnServerErrors);
}, ConnectionsManager.RequestFlagWithoutLogin | ConnectionsManager.RequestFlagFailOnServerErrors);*/
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
@@ -1991,7 +1991,7 @@ public class LoginActivity extends BaseFragment {
System.arraycopy(oldPasswordBytes, 0, hash, current_salt.length, oldPasswordBytes.length);
System.arraycopy(current_salt, 0, hash, hash.length - current_salt.length, current_salt.length);
final TLRPC.TL_auth_checkPassword req = new TLRPC.TL_auth_checkPassword();
/*final TLRPC.TL_auth_checkPassword req = new TLRPC.TL_auth_checkPassword();
req.password_hash = Utilities.computeSHA256(hash, 0, hash.length);
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
@@ -2035,7 +2035,7 @@ public class LoginActivity extends BaseFragment {
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);*/
}
@Override
@@ -2216,7 +2216,7 @@ public class LoginActivity extends BaseFragment {
return;
}
needShowProgress();
TLRPC.TL_auth_recoverPassword req = new TLRPC.TL_auth_recoverPassword();
/*TLRPC.TL_auth_recoverPassword req = new TLRPC.TL_auth_recoverPassword();
req.code = code;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
@@ -2260,7 +2260,7 @@ public class LoginActivity extends BaseFragment {
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);*/
}
@Override
@@ -2431,7 +2431,7 @@ public class LoginActivity extends BaseFragment {
req.first_name = firstNameField.getText().toString();
req.last_name = lastNameField.getText().toString();
needShowProgress();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@@ -2473,7 +2473,7 @@ public class LoginActivity extends BaseFragment {
}
});
}
}, ConnectionsManager.RequestFlagWithoutLogin | ConnectionsManager.RequestFlagFailOnServerErrors);
}, ConnectionsManager.RequestFlagWithoutLogin | ConnectionsManager.RequestFlagFailOnServerErrors);*/
}
@Override
@@ -1563,7 +1563,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
return;
}
final int currentReqId = ++lastReqId;
reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
reqId = 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
final ArrayList<MessageObject> messageObjects = new ArrayList<>();
@@ -1588,7 +1588,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors);
}, ConnectionsManager.RequestFlagFailOnServerErrors);*/
ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);
}
@@ -259,7 +259,7 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif
return;
}
reseting = true;
TLRPC.TL_account_resetNotifySettings req = new TLRPC.TL_account_resetNotifySettings();
/*TLRPC.TL_account_resetNotifySettings req = new TLRPC.TL_account_resetNotifySettings();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
@@ -282,7 +282,7 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif
}
});
}
});
});*/
} else if (i == inappSoundRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();