Commit 2cb6bb3e authored by DrKLO's avatar DrKLO

Merge branch 'dev'

parents d1c9175b d728d9c4
......@@ -81,7 +81,7 @@ android {
defaultConfig {
minSdkVersion 8
targetSdkVersion 19
versionCode 250
versionName "1.5.0"
versionCode 267
versionName "1.5.7"
}
}
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_PRELINK_MODULE := false
LOCAL_MODULE := tmessages
LOCAL_CFLAGS := -w -std=gnu99 -O3 -DNULL=0 -DSOCKLEN_T=socklen_t -DLOCALE_NOT_USED -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64
LOCAL_CFLAGS := -w -std=gnu99 -O2 -DNULL=0 -DSOCKLEN_T=socklen_t -DLOCALE_NOT_USED -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64 -DLOG_DISABLED
LOCAL_CFLAGS += -Drestrict='' -D__EMX__ -DOPUS_BUILD -DFIXED_POINT -DUSE_ALLOCA -DHAVE_LRINT -DHAVE_LRINTF -fno-math-errno
LOCAL_CFLAGS += -DANDROID_NDK -DDISABLE_IMPORTGL -fno-strict-aliasing -fprefetch-loop-arrays -DAVOID_TABLES -DANDROID_TILE_BASED_DECODE -DANDROID_ARMV6_IDCT
LOCAL_CPPFLAGS := -DBSD=1 -ffast-math -O3 -funroll-loops
LOCAL_LDLIBS := -llog -lm -ljnigraphics
LOCAL_CPPFLAGS := -DBSD=1 -ffast-math -O2 -funroll-loops
#LOCAL_LDLIBS := -llog
LOCAL_SRC_FILES := \
./opus/src/opus.c \
......
#include <jni.h>
#include <stdio.h>
#include <setjmp.h>
#include <android/bitmap.h>
#include <libjpeg/jpeglib.h>
#include "utils.h"
......@@ -17,23 +16,23 @@ METHODDEF(void) my_error_exit(j_common_ptr cinfo) {
longjmp(myerr->setjmp_buffer, 1);
}
JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jclass class, jstring path, jobject bitmap, int scale) {
JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jclass class, jstring path, jintArray bitmap, int scale, int format, int width, int height) {
AndroidBitmapInfo info;
int i;
if ((i = AndroidBitmap_getInfo(env, bitmap, &info)) >= 0) {
char *fileName = (*env)->GetStringUTFChars(env, path, NULL);
FILE *infile;
char *fileName = (*env)->GetStringUTFChars(env, path, NULL);
FILE *infile;
if ((infile = fopen(fileName, "rb"))) {
struct my_error_mgr jerr;
struct jpeg_decompress_struct cinfo;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
if ((infile = fopen(fileName, "rb"))) {
struct my_error_mgr jerr;
struct jpeg_decompress_struct cinfo;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
if (!setjmp(jerr.setjmp_buffer)) {
if (!setjmp(jerr.setjmp_buffer)) {
unsigned char *bitmapBuf = (*env)->GetPrimitiveArrayCritical(env, bitmap, 0);
if (bitmapBuf) {
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, infile);
......@@ -45,60 +44,60 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jcl
jpeg_start_decompress(&cinfo);
int row_stride = cinfo.output_width * cinfo.output_components;
JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
int stride = width;
if (format == 0) {
stride *= 4;
} else if (format == 1) {
stride *= 2;
}
unsigned char *pixels = bitmapBuf;
int rowCount = min(cinfo.output_height, height);
int colCount = min(cinfo.output_width, width);
unsigned char *pixels;
if ((i = AndroidBitmap_lockPixels(env, bitmap, &pixels)) >= 0) {
while (cinfo.output_scanline < rowCount) {
jpeg_read_scanlines(&cinfo, buffer, 1);
int rowCount = min(cinfo.output_height, info.height);
int colCount = min(cinfo.output_width, info.width);
while (cinfo.output_scanline < rowCount) {
jpeg_read_scanlines(&cinfo, buffer, 1);
if (info.format == ANDROID_BITMAP_FORMAT_RGBA_8888) {
if (cinfo.out_color_space == JCS_GRAYSCALE) {
for (i = 0; i < colCount; i++) {
float alpha = buffer[0][i] / 255.0f;
pixels[i * 4] *= alpha;
pixels[i * 4 + 1] *= alpha;
pixels[i * 4 + 2] *= alpha;
pixels[i * 4 + 3] = buffer[0][i];
}
} else {
int c = 0;
for (i = 0; i < colCount; i++) {
pixels[i * 4] = buffer[0][i * 3];
pixels[i * 4 + 1] = buffer[0][i * 3 + 1];
pixels[i * 4 + 2] = buffer[0][i * 3 + 2];
pixels[i * 4 + 3] = 255;
c += 4;
}
if (format == 0) {
if (cinfo.out_color_space == JCS_GRAYSCALE) {
for (i = 0; i < colCount; i++) {
float alpha = buffer[0][i] / 255.0f;
pixels[i * 4] *= alpha;
pixels[i * 4 + 1] *= alpha;
pixels[i * 4 + 2] *= alpha;
pixels[i * 4 + 3] = buffer[0][i];
}
} else {
int c = 0;
for (i = 0; i < colCount; i++) {
pixels[i * 4] = buffer[0][i * 3 + 2];
pixels[i * 4 + 1] = buffer[0][i * 3 + 1];
pixels[i * 4 + 2] = buffer[0][i * 3];
pixels[i * 4 + 3] = 255;
c += 4;
}
} else if (info.format == ANDROID_BITMAP_FORMAT_RGB_565) {
}
} else if (format == 1) {
pixels += info.stride;
}
AndroidBitmap_unlockPixels(env, bitmap);
} else {
throwException(env, "AndroidBitmap_lockPixels() failed ! error=%d", i);
pixels += stride;
}
(*env)->ReleasePrimitiveArrayCritical(env, bitmap, bitmapBuf, 0);
jpeg_finish_decompress(&cinfo);
} else {
throwException(env, "the JPEG code has signaled an error");
throwException(env, "can't get bitmap buff");
}
jpeg_destroy_decompress(&cinfo);
fclose(infile);
} else {
throwException(env, "can't open %s\n", fileName);
throwException(env, "the JPEG code has signaled an error");
}
(*env)->ReleaseStringUTFChars(env, path, fileName);
jpeg_destroy_decompress(&cinfo);
fclose(infile);
} else {
throwException(env, "AndroidBitmap_getInfo() failed ! error=%d", i);
throwException(env, "can't open %s", fileName);
}
(*env)->ReleaseStringUTFChars(env, path, fileName);
}
......@@ -5,10 +5,17 @@
#include <jni.h>
#define LOG_TAG "tmessages_native"
#ifndef LOG_DISABLED
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
#else
#define LOGI(...)
#define LOGD(...)
#define LOGE(...)
#define LOGV(...)
#endif
#ifndef max
#define max(x, y) ((x) > (y)) ? (x) : (y)
......
......@@ -17,7 +17,7 @@ import java.util.Map;
public class SQLiteDatabase {
private final int sqliteHandle;
private final Map<String, SQLitePreparedStatement> preparedMap;
private final Map<String, SQLitePreparedStatement> preparedMap = new HashMap<String, SQLitePreparedStatement>();
private boolean isOpen = false;
private boolean inTransaction = false;
......@@ -28,7 +28,6 @@ public class SQLiteDatabase {
public SQLiteDatabase(String fileName) throws SQLiteException {
sqliteHandle = opendb(fileName, ApplicationLoader.applicationContext.getFilesDir().getPath());
isOpen = true;
preparedMap = new HashMap<String, SQLitePreparedStatement>();
}
public boolean tableExists(String tableName) throws SQLiteException {
......@@ -47,7 +46,7 @@ public class SQLiteDatabase {
}
}
public SQLitePreparedStatement executeFast(String sql) throws SQLiteException{
public SQLitePreparedStatement executeFast(String sql) throws SQLiteException {
return new SQLitePreparedStatement(this, sql, true);
}
......@@ -64,29 +63,6 @@ public class SQLiteDatabase {
}
}
public int executeIntOrThrow(String sql, Object... args) throws SQLiteException, SQLiteNoRowException {
checkOpened();
Integer val = executeInt(sql, args);
if (val != null) {
return val;
}
throw new SQLiteNoRowException();
}
public String executeString(String sql, Object... args) throws SQLiteException {
checkOpened();
SQLiteCursor cursor = query(sql, args);
try {
if (!cursor.next()) {
return null;
}
return cursor.stringValue(0);
} finally {
cursor.dispose();
}
}
public SQLiteCursor query(String sql, Object... args) throws SQLiteException {
checkOpened();
SQLitePreparedStatement stmt = preparedMap.get(sql);
......@@ -110,6 +86,7 @@ public class SQLiteDatabase {
for (SQLitePreparedStatement stmt : preparedMap.values()) {
stmt.finalizeQuery();
}
commitTransaction();
closedb(sqliteHandle);
} catch (SQLiteException e) {
FileLog.e("tmessages", e.getMessage(), e);
......@@ -139,6 +116,9 @@ public class SQLiteDatabase {
}
public void commitTransaction() {
if (!inTransaction) {
return;
}
inTransaction = false;
commitTransaction(sqliteHandle);
}
......
......@@ -17,6 +17,7 @@ public class BuffersStorage {
private final ArrayList<ByteBufferDesc> freeBuffers4096;
private final ArrayList<ByteBufferDesc> freeBuffers16384;
private final ArrayList<ByteBufferDesc> freeBuffers32768;
private final ArrayList<ByteBufferDesc> freeBuffersBig;
private static volatile BuffersStorage Instance = null;
public static BuffersStorage getInstance() {
......@@ -38,6 +39,7 @@ public class BuffersStorage {
freeBuffers4096 = new ArrayList<ByteBufferDesc>();
freeBuffers16384 = new ArrayList<ByteBufferDesc>();
freeBuffers32768 = new ArrayList<ByteBufferDesc>();
freeBuffersBig = new ArrayList<ByteBufferDesc>();
for (int a = 0; a < 5; a++) {
freeBuffers128.add(new ByteBufferDesc(128));
......@@ -113,6 +115,17 @@ public class BuffersStorage {
buffer = new ByteBufferDesc(40000);
FileLog.e("tmessages", "create new 40000 buffer");
}
} else if (size <= 280000) {
synchronized (freeBuffersBig) {
if (freeBuffersBig.size() > 0) {
buffer = freeBuffersBig.get(0);
freeBuffersBig.remove(0);
}
}
if (buffer == null) {
buffer = new ByteBufferDesc(280000);
FileLog.e("tmessages", "create new big buffer");
}
} else {
buffer = new ByteBufferDesc(size);
}
......@@ -126,23 +139,39 @@ public class BuffersStorage {
}
if (buffer.buffer.capacity() == 128) {
synchronized (freeBuffers128) {
freeBuffers128.add(buffer);
if (freeBuffers128.size() < 10) {
freeBuffers128.add(buffer);
}
}
} else if (buffer.buffer.capacity() == 1024 + 200) {
synchronized (freeBuffers1024) {
freeBuffers1024.add(buffer);
if (freeBuffers1024.size() < 10) {
freeBuffers1024.add(buffer);
}
}
} else if (buffer.buffer.capacity() == 4096 + 200) {
synchronized (freeBuffers4096) {
freeBuffers4096.add(buffer);
if (freeBuffers4096.size() < 10) {
freeBuffers4096.add(buffer);
}
}
} else if (buffer.buffer.capacity() == 16384 + 200) {
synchronized (freeBuffers16384) {
freeBuffers16384.add(buffer);
if (freeBuffers16384.size() < 10) {
freeBuffers16384.add(buffer);
}
}
} else if (buffer.buffer.capacity() == 40000) {
synchronized (freeBuffers32768) {
freeBuffers32768.add(buffer);
if (freeBuffers32768.size() < 10) {
freeBuffers32768.add(buffer);
}
}
} else if (buffer.buffer.capacity() == 280000) {
synchronized (freeBuffersBig) {
if (freeBuffersBig.size() < 4) {
freeBuffersBig.add(buffer);
}
}
}
}
......
......@@ -35,8 +35,8 @@ public class Datacenter {
private volatile int currentAddressNum = 0;
public TcpConnection connection;
public TcpConnection downloadConnection;
public TcpConnection uploadConnection;
private ArrayList<TcpConnection> downloadConnections = new ArrayList<TcpConnection>();
private TcpConnection uploadConnection;
public TcpConnection pushConnection;
private ArrayList<ServerSalt> authServerSaltSet = new ArrayList<ServerSalt>();
......@@ -319,4 +319,81 @@ public class Datacenter {
}
return false;
}
public void suspendConnections() {
if (connection != null) {
connection.suspendConnection(true);
}
if (uploadConnection != null) {
uploadConnection.suspendConnection(true);
}
for (TcpConnection downloadConnection : downloadConnections) {
downloadConnection.suspendConnection(true);
}
}
public void getSessions(ArrayList<Long> sessions) {
if (connection != null) {
sessions.add(connection.getSissionId());
}
if (uploadConnection != null) {
sessions.add(uploadConnection.getSissionId());
}
for (TcpConnection downloadConnection : downloadConnections) {
sessions.add(downloadConnection.getSissionId());
}
}
public void recreateSessions() {
if (connection != null) {
connection.recreateSession();
}
if (uploadConnection != null) {
uploadConnection.recreateSession();
}
for (TcpConnection downloadConnection : downloadConnections) {
downloadConnection.recreateSession();
}
}
public TcpConnection getDownloadConnection(int num, TcpConnection.TcpConnectionDelegate delegate) {
if (num >= 0 && authKey != null) {
TcpConnection downloadConnection = null;
if (num < downloadConnections.size()) {
downloadConnection = downloadConnections.get(num);
} else {
downloadConnection = new TcpConnection(datacenterId);
downloadConnection.delegate = delegate;
downloadConnection.transportRequestClass = RPCRequest.RPCRequestClassDownloadMedia;
downloadConnections.add(downloadConnection);
}
downloadConnection.connect();
return downloadConnection;
}
return null;
}
public TcpConnection getUploadConnection(TcpConnection.TcpConnectionDelegate delegate) {
if (authKey != null) {
if (uploadConnection == null) {
uploadConnection = new TcpConnection(datacenterId);
uploadConnection.delegate = delegate;
uploadConnection.transportRequestClass = RPCRequest.RPCRequestClassUploadMedia;
}
uploadConnection.connect();
}
return uploadConnection;
}
public TcpConnection getGenericConnection(TcpConnection.TcpConnectionDelegate delegate) {
if (authKey != null) {
if (connection == null) {
connection = new TcpConnection(datacenterId);
connection.delegate = delegate;
connection.transportRequestClass = RPCRequest.RPCRequestClassGeneric;
}
connection.connect();
}
return connection;
}
}
......@@ -11,7 +11,6 @@ package org.telegram.messenger;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
public class DispatchQueue extends Thread {
public volatile Handler handler = null;
......@@ -68,6 +67,12 @@ public class DispatchQueue extends Thread {
}
}
public void cleanupQueue() {
if (handler != null) {
handler.removeCallbacksAndMessages(null);
}
}
public void run() {
Looper.prepare();
synchronized (handlerSyncObject) {
......
......@@ -85,6 +85,6 @@ public class ExportAuthorizationAction extends Action {
}
}
}
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassEnableUnauthorized, datacenter.datacenterId);
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassEnableUnauthorized | RPCRequest.RPCRequestClassWithoutLogin, datacenter.datacenterId);
}
}
......@@ -337,11 +337,11 @@ public class FileLoader {
return memCache.get(key) != null;
}
public void uploadFile(final String location, final byte[] key, final byte[] iv) {
public void uploadFile(final String location, final boolean encrypted) {
fileLoaderQueue.postRunnable(new Runnable() {
@Override
public void run() {
if (key != null) {
if (encrypted) {
if (uploadOperationPathsEnc.containsKey(location)) {
return;
}
......@@ -350,8 +350,8 @@ public class FileLoader {
return;
}
}
FileUploadOperation operation = new FileUploadOperation(location, key, iv);
if (key != null) {
FileUploadOperation operation = new FileUploadOperation(location, encrypted);
if (encrypted) {
uploadOperationPathsEnc.put(location, operation);
} else {
uploadOperationPaths.put(location, operation);
......@@ -369,7 +369,7 @@ public class FileLoader {
fileProgresses.remove(location);
}
});
if (key != null) {
if (encrypted) {
uploadOperationPathsEnc.remove(location);
} else {
uploadOperationPaths.remove(location);
......@@ -396,11 +396,11 @@ public class FileLoader {
public void run() {
fileProgresses.remove(location);
if (operation.state != 2) {
NotificationCenter.getInstance().postNotificationName(FileDidFailUpload, location, key != null);
NotificationCenter.getInstance().postNotificationName(FileDidFailUpload, location, encrypted);
}
}
});
if (key != null) {
if (encrypted) {
uploadOperationPathsEnc.remove(location);
} else {
uploadOperationPaths.remove(location);
......@@ -428,7 +428,7 @@ public class FileLoader {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().postNotificationName(FileUploadProgressChanged, location, progress, key != null);
NotificationCenter.getInstance().postNotificationName(FileUploadProgressChanged, location, progress, encrypted);
}
});
}
......
......@@ -44,18 +44,22 @@ public class FileLog {
return;
}
dateFormat = FastDateFormat.getInstance("dd_MM_yyyy_HH_mm_ss", Locale.US);
File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null);
if (sdCard == null) {
return;
}
File dir = new File(sdCard.getAbsolutePath() + "/logs");
if (dir == null) {
return;
}
dir.mkdirs();
currentFile = new File(dir, dateFormat.format(System.currentTimeMillis()) + ".txt");
if (currentFile == null) {
return;
try {
File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null);
if (sdCard == null) {
return;
}
File dir = new File(sdCard.getAbsolutePath() + "/logs");
if (dir == null) {
return;
}
dir.mkdirs();
currentFile = new File(dir, dateFormat.format(System.currentTimeMillis()) + ".txt");
if (currentFile == null) {
return;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
currentFile.createNewFile();
......@@ -110,7 +114,7 @@ public class FileLog {
}
}
public static void e(final String tag, final Exception e) {
public static void e(final String tag, final Throwable e) {
if (!BuildVars.DEBUG_VERSION) {
return;
}
......
......@@ -30,6 +30,7 @@ public class FileUploadOperation {
private long currentUploaded = 0;
private byte[] key;
private byte[] iv;
private byte[] ivChange;
private int fingerprint;
private boolean isBigFile = false;
FileInputStream stream;
......@@ -41,12 +42,15 @@ public class FileUploadOperation {
public abstract void didChangedUploadProgress(FileUploadOperation operation, float progress);
}
public FileUploadOperation(String location, byte[] keyarr, byte[] ivarr) {
public FileUploadOperation(String location, boolean encrypted) {
uploadingFilePath = location;
if (ivarr != null && keyarr != null) {
if (encrypted) {
iv = new byte[32];
key = keyarr;
System.arraycopy(ivarr, 0, iv, 0, 32);
key = new byte[32];
ivChange = new byte[32];
Utilities.random.nextBytes(iv);
Utilities.random.nextBytes(key);
System.arraycopy(iv, 0, ivChange, 0, 32);
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] arr = new byte[64];
......@@ -106,7 +110,7 @@ public class FileUploadOperation {
isBigFile = true;
}
uploadChunkSize = (int)Math.max(32, Math.ceil(totalFileSize / (1024.0f * 3000)));
uploadChunkSize = (int) Math.max(32, Math.ceil(totalFileSize / (1024.0f * 3000)));
if (1024 % uploadChunkSize != 0) {
int chunkSize = 64;
while (uploadChunkSize > chunkSize) {
......@@ -116,7 +120,7 @@ public class FileUploadOperation {
}
uploadChunkSize *= 1024;
totalPartsCount = (int)Math.ceil((float)totalFileSize / (float)uploadChunkSize);
totalPartsCount = (int) Math.ceil((float) totalFileSize / (float) uploadChunkSize);
readBuffer = new byte[uploadChunkSize];
}
......@@ -134,7 +138,7 @@ public class FileUploadOperation {
for (int a = 0; a < toAdd; a++) {
sendBuffer.writeByte(0);
}
Utilities.aesIgeEncryption2(sendBuffer.buffer, key, iv, true, true, readed + toAdd);
Utilities.aesIgeEncryption2(sendBuffer.buffer, key, ivChange, true, true, readed + toAdd);
}
sendBuffer.rewind();
if (!isBigFile) {
......@@ -161,55 +165,57 @@ public class FileUploadOperation {
return;
}
requestToken = ConnectionsManager.getInstance().performRpc(finalRequest, new RPCRequest.RPCRequestDelegate() {
@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, (float)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);
} 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);
}
@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, (float) currentUploaded / (float) totalFileSize);
if (isLastPart) {
state = 3;
if (key == null) {
TLRPC.InputFile result;
if (isBigFile) {
result = new TLRPC.TL_inputFileBig();
} else {
startUploadRequest();
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);
} else {
delegate.didFailedUploadingFile(FileUploadOperation.this);
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;
result.iv = iv;
result.key = key;
delegate.didFinishUploadingFile(FileUploadOperation.this, null, result);
}
} else {
delegate.didFailedUploadingFile(FileUploadOperation.this);
startUploadRequest();
}
} else {
delegate.didFailedUploadingFile(FileUploadOperation.this);
}
}, new RPCRequest.RPCProgressDelegate() {
@Override
public void progress(int length, int progress) {
} else {
delegate.didFailedUploadingFile(FileUploadOperation.this);
}
}
}, new RPCRequest.RPCProgressDelegate() {
@Override
public void progress(int length, int progress) {
}
}, null, true, RPCRequest.RPCRequestClassUploadMedia, ConnectionsManager.DEFAULT_DATACENTER_ID);
}
}, null, true, RPCRequest.RPCRequestClassUploadMedia, ConnectionsManager.DEFAULT_DATACENTER_ID);
}
}
......@@ -12,7 +12,6 @@ import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import org.json.JSONObject;
import org.telegram.ui.ApplicationLoader;
......@@ -20,7 +19,6 @@ import org.telegram.ui.ApplicationLoader;
public class GcmBroadcastReceiver extends BroadcastReceiver {
public static final int NOTIFICATION_ID = 1;
private static PowerManager.WakeLock wakeLock = null;
private static final Integer sync = 1;
@Override
......@@ -28,27 +26,6 @@ public class GcmBroadcastReceiver extends BroadcastReceiver {
FileLog.d("tmessages", "GCM received intent: " + intent);
if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
synchronized (sync) {
try {
if (wakeLock == null) {
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
}
if (!wakeLock.isHeld()) {
wakeLock.acquire(5000);
}
} catch (Exception e) {
try {
if (wakeLock != null) {
wakeLock.release();
}
} catch (Exception e2) {
FileLog.e("tmessages", e2);
}
FileLog.e("tmessages", e);
}
}
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
......
......@@ -52,9 +52,9 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
void beginHandshake(boolean dropConnection) {
if (datacenter.connection == null) {
datacenter.connection = new TcpConnection(datacenter.datacenterId);
datacenter.connection.delegate = this;
datacenter.connection.transportRequestClass = RPCRequest.RPCRequestClassGeneric;
}
datacenter.connection.delegate = this;
processedMessageIds = new ArrayList<Long>();
authNonce = null;
......@@ -209,7 +209,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
ByteBuffer data = ByteBuffer.wrap(resPq.pq);
final long pqf = data.getLong();
final long messageIdf = messageId;
Utilities.globalQueue.postRunnable(new Runnable() {
new Thread(new Runnable() {
@Override
public void run() {
......@@ -281,7 +281,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
}
});
}
});
}).start();
} else {
FileLog.e("tmessages", "***** Error: invalid handshake nonce");
beginHandshake(false);
......@@ -566,8 +566,14 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
}
@Override
public void tcpConnectionClosed(TcpConnection connection) {
public void tcpConnectionClosed(final TcpConnection connection) {
wasDisconnect = true;
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
connection.connect();
}
}, 1000);
}
@Override
......@@ -591,9 +597,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
@Override
public void tcpConnectionReceivedData(TcpConnection connection, ByteBufferDesc data, int length) {
long keyId = data.readInt64();
if (keyId == 0) {
long messageId = data.readInt64();
if (processedMessageIds.contains(messageId)) {
......
......@@ -1024,7 +1024,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
fileDecodingQueue.postRunnable(new Runnable() {
@Override
public void run() {
if (playingMessageObject.audioProgress != 0) {
if (playingMessageObject != null && playingMessageObject.audioProgress != 0) {
lastPlayPcm = (long)(currentTotalPcmDuration * playingMessageObject.audioProgress);
seekOpusFile(playingMessageObject.audioProgress);
}
......@@ -1143,7 +1143,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
recordingAudio = new TLRPC.TL_audio();
recordingAudio.dc_id = Integer.MIN_VALUE;
recordingAudio.id = UserConfig.lastLocalId;
recordingAudio.user_id = UserConfig.clientUserId;
recordingAudio.user_id = UserConfig.getClientUserId();
UserConfig.lastLocalId--;
UserConfig.saveConfig(false);
......@@ -1352,7 +1352,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
final ProgressDialog finalProgress = progressDialog;
Utilities.globalQueue.postRunnable(new Runnable() {
new Thread(new Runnable() {
@Override
public void run() {
try {
......@@ -1427,7 +1427,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
});
}
}
});
}).start();
}
}
......@@ -1536,7 +1536,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
return false;
}
public static String copyDocumentToCache(Uri uri) {
public static String copyDocumentToCache(Uri uri, String ext) {
ParcelFileDescriptor parcelFD = null;
FileInputStream input = null;
FileOutputStream output = null;
......@@ -1545,7 +1545,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
UserConfig.lastLocalId--;
parcelFD = ApplicationLoader.applicationContext.getContentResolver().openFileDescriptor(uri, "r");
input = new FileInputStream(parcelFD.getFileDescriptor());
File f = new File(Utilities.getCacheDir(), String.format(Locale.US, "%d.gif", id));
File f = new File(Utilities.getCacheDir(), String.format(Locale.US, "%d.%s", id, ext));
output = new FileOutputStream(f);
input.getChannel().transferTo(0, input.getChannel().size(), output.getChannel());
UserConfig.saveConfig(false);
......
......@@ -36,6 +36,11 @@ public class MessagesStorage {
public static byte[] secretPBytes = null;
public static int secretG = 0;
private int lastSavedSeq = 0;
private int lastSavedPts = 0;
private int lastSavedDate = 0;
private int lastSavedQts = 0;
public static final int wallpapersDidLoaded = 171;
private static volatile MessagesStorage Instance = null;
......@@ -92,6 +97,8 @@ public class MessagesStorage {
database.executeFast("CREATE TABLE user_contacts_v6(uid INTEGER PRIMARY KEY, fname TEXT, sname TEXT)").stepThis().dispose();
database.executeFast("CREATE TABLE user_phones_v6(uid INTEGER, phone TEXT, sphone TEXT, deleted INTEGER, PRIMARY KEY (uid, phone))").stepThis().dispose();
database.executeFast("CREATE TABLE sent_files_v2(uid TEXT, type INTEGER, data BLOB, PRIMARY KEY (uid, type))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms ON randoms(mid);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v6(sphone, deleted);").stepThis().dispose();
......@@ -161,6 +168,8 @@ public class MessagesStorage {
database.executeFast("CREATE INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v6(sphone, deleted);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms ON randoms(mid);").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS sent_files_v2(uid TEXT, type INTEGER, data BLOB, PRIMARY KEY (uid, type))").stepThis().dispose();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
......@@ -168,6 +177,7 @@ public class MessagesStorage {
}
public void cleanUp() {
storageQueue.cleanupQueue();
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
......@@ -176,6 +186,12 @@ public class MessagesStorage {
lastPtsValue = 0;
lastQtsValue = 0;
lastSecretVersion = 0;
lastSavedSeq = 0;
lastSavedPts = 0;
lastSavedDate = 0;
lastSavedQts = 0;
secretPBytes = null;
secretG = 0;
if (database != null) {
......@@ -186,6 +202,7 @@ public class MessagesStorage {
cacheFile.delete();
cacheFile = null;
}
storageQueue.cleanupQueue();
openDatabase();
}
});
......@@ -218,6 +235,9 @@ public class MessagesStorage {
@Override
public void run() {
try {
if (lastSavedSeq == seq && lastSavedPts == pts && lastSavedDate == date && lastQtsValue == qts) {
return;
}
SQLitePreparedStatement state = database.executeFast("UPDATE params SET seq = ?, pts = ?, date = ?, qts = ? WHERE id = 1");
state.bindInteger(1, seq);
state.bindInteger(2, pts);
......@@ -225,6 +245,10 @@ public class MessagesStorage {
state.bindInteger(4, qts);
state.step();
state.dispose();
lastSavedSeq = seq;
lastSavedPts = pts;
lastSavedDate = date;
lastSavedQts = qts;
} catch (Exception e) {
FileLog.e("tmessages", e);
}
......@@ -781,7 +805,7 @@ public class MessagesStorage {
if (userData != null) {
SerializedData data = new SerializedData(userData);
TLRPC.User user = (TLRPC.User)TLClassStore.Instance().TLdeserialize(data, data.readInt32());
if (user.id == UserConfig.clientUserId) {
if (user.id == UserConfig.getClientUserId()) {
continue;
}
if (user.status != null) {
......@@ -1018,7 +1042,7 @@ public class MessagesStorage {
String uids = "";
while (cursor.next()) {
int user_id = cursor.intValue(0);
if (user_id == UserConfig.clientUserId) {
if (user_id == UserConfig.getClientUserId()) {
continue;
}
TLRPC.TL_contact contact = new TLRPC.TL_contact();
......@@ -1415,6 +1439,73 @@ public class MessagesStorage {
}
}
public TLObject getSentFile(final String path, final int type) {
if (path == null) {
return null;
}
final Semaphore semaphore = new Semaphore(0);
final ArrayList<TLObject> result = new ArrayList<TLObject>();
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
String id = Utilities.MD5(path);
if (id != null) {
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM sent_files_v2 WHERE uid = '%s' AND type = %d", id, type));
if (cursor.next()) {
byte[] fileData = cursor.byteArrayValue(0);
if (fileData != null) {
SerializedData data = new SerializedData(fileData);
TLObject file = TLClassStore.Instance().TLdeserialize(data, data.readInt32());
if (file != null) {
result.add(file);
}
}
}
cursor.dispose();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
semaphore.release();
}
}
});
try {
semaphore.acquire();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
return !result.isEmpty() ? result.get(0) : null;
}
public void putSentFile(final String path, final TLObject file, final int type) {
if (path == null || file == null) {
return;
}
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
String id = Utilities.MD5(path);
if (id != null) {
SQLitePreparedStatement state = database.executeFast("REPLACE INTO sent_files_v2 VALUES(?, ?, ?)");
state.requery();
SerializedData data = new SerializedData();
file.serializeToStream(data);
state.bindString(1, id);
state.bindInteger(2, type);
state.bindByteArray(3, data.toByteArray());
state.step();
state.dispose();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
public void updateEncryptedChatTTL(final TLRPC.EncryptedChat chat) {
if (chat == null) {
return;
......@@ -1838,6 +1929,7 @@ public class MessagesStorage {
state.bindInteger(2, count);
state.step();
}
cursor.dispose();
}
state.dispose();
}
......@@ -2484,7 +2576,7 @@ public class MessagesStorage {
ArrayList<TLRPC.EncryptedChat> encryptedChats = new ArrayList<TLRPC.EncryptedChat>();
try {
ArrayList<Integer> usersToLoad = new ArrayList<Integer>();
usersToLoad.add(UserConfig.clientUserId);
usersToLoad.add(UserConfig.getClientUserId());
ArrayList<Integer> chatsToLoad = new ArrayList<Integer>();
ArrayList<Integer> encryptedToLoad = new ArrayList<Integer>();
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid ORDER BY d.date DESC LIMIT %d,%d", offset, count));
......
......@@ -22,9 +22,9 @@ import java.util.zip.ZipFile;
public class NativeLoader {
private static final long sizes[] = new long[] {
922256, //armeabi
991908, //armeabi-v7a
1713204, //x86
795280, //armeabi
844452, //armeabi-v7a
1242164, //x86
0, //mips
};
......@@ -48,6 +48,53 @@ public class NativeLoader {
return null;
}
private static boolean loadFromZip(Context context, File destLocalFile, String folder) {
ZipFile zipFile = null;
InputStream stream = null;
try {
zipFile = new ZipFile(context.getApplicationInfo().sourceDir);
ZipEntry entry = zipFile.getEntry("lib/" + folder + "/libtmessages.so");
if (entry == null) {
throw new Exception("Unable to find file in apk:" + "lib/" + folder + "/libtmessages.so");
}
stream = zipFile.getInputStream(entry);
OutputStream out = new FileOutputStream(destLocalFile);
byte[] buf = new byte[4096];
int len;
while ((len = stream.read(buf)) > 0) {
Thread.yield();
out.write(buf, 0, len);
}
out.close();
try {
System.load(destLocalFile.getAbsolutePath());
nativeLoaded = true;
} catch (Error e) {
FileLog.e("tmessages", e);
}
return true;
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
if (zipFile != null) {
try {
zipFile.close();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
return false;
}
public static synchronized void initNativeLibs(Context context) {
if (nativeLoaded) {
......@@ -87,6 +134,12 @@ public class NativeLoader {
libSize2 = sizes[1];
}
String javaArch = System.getProperty("os.arch");
if (javaArch != null && javaArch.contains("686")) {
folder = "x86";
libSize = sizes[2];
}
File destFile = getNativeLibraryDir(context);
if (destFile != null) {
destFile = new File(destFile, "libtmessages.so");
......@@ -96,22 +149,22 @@ public class NativeLoader {
System.loadLibrary("tmessages");
nativeLoaded = true;
return;
} catch (Exception e) {
e.printStackTrace();
} catch (Error e) {
FileLog.e("tmessages", e);
}
}
}
File destLocalFile = new File(context.getFilesDir().getAbsolutePath() + "/libtmessages.so");
if (destLocalFile.exists()) {
if (destLocalFile != null && destLocalFile.exists()) {
if (destLocalFile.length() == libSize) {
try {
FileLog.d("tmessages", "Load local lib");
System.load(destLocalFile.getAbsolutePath());
nativeLoaded = true;
return;
} catch (Exception e) {
e.printStackTrace();
} catch (Error e) {
FileLog.e("tmessages", e);
}
} else {
destLocalFile.delete();
......@@ -120,51 +173,24 @@ public class NativeLoader {
FileLog.e("tmessages", "Library not found, arch = " + folder);
ZipFile zipFile = null;
InputStream stream = null;
try {
zipFile = new ZipFile(context.getApplicationInfo().sourceDir);
ZipEntry entry = zipFile.getEntry("lib/" + folder + "/libtmessages.so");
if (entry == null) {
throw new Exception("Unable to find file in apk:" + "lib/" + folder + "/libtmessages.so");
}
stream = zipFile.getInputStream(entry);
OutputStream out = new FileOutputStream(destLocalFile);
byte[] buf = new byte[4096];
int len;
while ((len = stream.read(buf)) > 0) {
Thread.yield();
out.write(buf, 0, len);
}
out.close();
System.load(destLocalFile.getAbsolutePath());
nativeLoaded = true;
return;
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
if (zipFile != null) {
try {
zipFile.close();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
if (!loadFromZip(context, destLocalFile, folder)) {
folder = "x86";
destLocalFile = new File(context.getFilesDir().getAbsolutePath() + "/libtmessages86.so");
if (!loadFromZip(context, destLocalFile, folder)) {
destLocalFile = new File(context.getFilesDir().getAbsolutePath() + "/libtmessagesarm.so");
folder = "armeabi";
loadFromZip(context, destLocalFile, folder);
}
}
} catch (Throwable e) {
e.printStackTrace();
}
System.loadLibrary("tmessages");
nativeLoaded = true;
try {
System.loadLibrary("tmessages");
nativeLoaded = true;
} catch (Error e) {
FileLog.e("tmessages", e);
}
}
}
......@@ -28,6 +28,8 @@ public class RPCRequest {
public static int RPCRequestClassFailOnServerErrors = 16;
public static int RPCRequestClassCanCompress = 32;
public static int RPCRequestClassPush = 64;
public static int RPCRequestClassWithoutLogin = 128;
public static int RPCRequestClassDownloadMedia2 = 256;
static int RPCRequestClassTransportMask = (RPCRequestClassGeneric | RPCRequestClassDownloadMedia | RPCRequestClassUploadMedia);
......
......@@ -19,9 +19,13 @@ public class ScreenReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
FileLog.e("tmessages", "screen off");
if (ConnectionsManager.lastPauseTime == 0) {
ConnectionsManager.lastPauseTime = System.currentTimeMillis();
}
ApplicationLoader.isScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
FileLog.e("tmessages", "screen on");
ConnectionsManager.resetLastPauseTime();
ApplicationLoader.isScreenOn = true;
}
}
......
......@@ -9,6 +9,8 @@
package org.telegram.messenger;
public class TLObject {
public boolean disableFree = false;
public TLObject () {
}
......
......@@ -3783,14 +3783,6 @@ public class TLRPC {
}
}
public static class InputEncryptedFile extends TLObject {
public long id;
public long access_hash;
public int parts;
public int key_fingerprint;
public String md5_checksum;
}
public static class TL_inputEncryptedFile extends InputEncryptedFile {
public static int constructor = 0x5a17b5e5;
......@@ -8144,6 +8136,9 @@ public class TLRPC {
@Override
public void freeResources() {
if (disableFree) {
return;
}
if (bytes != null) {
BuffersStorage.getInstance().reuseFreeBuffer(bytes);
bytes = null;
......@@ -8295,6 +8290,9 @@ public class TLRPC {
@Override
public void freeResources() {
if (disableFree) {
return;
}
if (result != null) {
result.freeResources();
}
......@@ -8834,7 +8832,7 @@ public class TLRPC {
}
}
public static class TL_documentEncrypted extends Document {
public static class TL_documentEncrypted extends TL_document {
public static int constructor = 0x55555556;
......@@ -8868,7 +8866,7 @@ public class TLRPC {
}
}
public static class TL_videoEncrypted extends Video {
public static class TL_videoEncrypted extends TL_video {
public static int constructor = 0x55555553;
......@@ -9179,6 +9177,9 @@ public class TLRPC {
@Override
public void freeResources() {
if (disableFree) {
return;
}
if (bytes != null) {
BuffersStorage.getInstance().reuseFreeBuffer(bytes);
bytes = null;
......@@ -9206,10 +9207,23 @@ public class TLRPC {
@Override
public void freeResources() {
if (disableFree) {
return;
}
if (bytes != null) {
BuffersStorage.getInstance().reuseFreeBuffer(bytes);
bytes = null;
}
}
}
public static class InputEncryptedFile extends TLObject {
public long id;
public long access_hash;
public int parts;
public int key_fingerprint;
public String md5_checksum;
public byte[] key;
public byte[] iv;
}
}
......@@ -135,7 +135,7 @@ public class TcpConnection extends ConnectionContext {
client.addListener(TcpConnection.this);
if ((transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) {
if (isNextPort) {
client.setTimeout(15000);
client.setTimeout(20000);
} else {
client.setTimeout(30000);
}
......@@ -424,7 +424,7 @@ public class TcpConnection extends ConnectionContext {
datacenter.storeCurrentAddressAndPortNum();
isNextPort = false;
if ((transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) {
client.setTimeout(40000);
client.setTimeout(60000 * 3 + 20000);
} else {
client.setTimeout(25000);
}
......
......@@ -17,9 +17,7 @@ import org.telegram.ui.ApplicationLoader;
import java.io.File;
public class UserConfig {
public static TLRPC.User currentUser;
public static int clientUserId = 0;
public static boolean clientActivated = false;
private static TLRPC.User currentUser;
public static boolean registeredForPush = false;
public static boolean registeredForInternalPush = false;
public static String pushString = "";
......@@ -62,8 +60,6 @@ public class UserConfig {
if (withFile) {
SerializedData data = new SerializedData();
currentUser.serializeToStream(data);
clientUserId = currentUser.id;
clientActivated = true;
String userString = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT);
editor.putString("user", userString);
}
......@@ -80,6 +76,30 @@ public class UserConfig {
}
}
public static boolean isClientActivated() {
synchronized (sync) {
return currentUser != null;
}
}
public static int getClientUserId() {
synchronized (sync) {
return currentUser != null ? currentUser.id : 0;
}
}
public static TLRPC.User getCurrentUser() {
synchronized (sync) {
return currentUser;
}
}
public static void setCurrentUser(TLRPC.User user) {
synchronized (sync) {
currentUser = user;
}
}
public static void loadConfig() {
synchronized (sync) {
final File configFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "user.dat");
......@@ -90,8 +110,6 @@ public class UserConfig {
if (ver == 1) {
int constructor = data.readInt32();
currentUser = (TLRPC.TL_userSelf)TLClassStore.Instance().TLdeserialize(data, constructor);
clientUserId = currentUser.id;
clientActivated = true;
MessagesStorage.lastDateValue = data.readInt32();
MessagesStorage.lastPtsValue = data.readInt32();
MessagesStorage.lastSeqValue = data.readInt32();
......@@ -119,8 +137,6 @@ public class UserConfig {
} else if (ver == 2) {
int constructor = data.readInt32();
currentUser = (TLRPC.TL_userSelf)TLClassStore.Instance().TLdeserialize(data, constructor);
clientUserId = currentUser.id;
clientActivated = true;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("userconfing", Context.MODE_PRIVATE);
registeredForPush = preferences.getBoolean("registeredForPush", false);
......@@ -164,21 +180,13 @@ public class UserConfig {
if (userBytes != null) {
SerializedData data = new SerializedData(userBytes);
currentUser = (TLRPC.TL_userSelf)TLClassStore.Instance().TLdeserialize(data, data.readInt32());
clientUserId = currentUser.id;
clientActivated = true;
}
}
if (currentUser == null) {
clientActivated = false;
clientUserId = 0;
}
}
}
}
public static void clearConfig() {
clientUserId = 0;
clientActivated = false;
currentUser = null;
registeredForInternalPush = false;
registeredForPush = false;
......
......@@ -15,8 +15,8 @@ import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Typeface;
import android.net.Uri;
......@@ -34,6 +34,7 @@ import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import net.hockeyapp.android.CrashManager;
import net.hockeyapp.android.CrashManagerListener;
import net.hockeyapp.android.UpdateManager;
import org.telegram.ui.ApplicationLoader;
......@@ -87,6 +88,8 @@ public class Utilities {
public static volatile DispatchQueue stageQueue = new DispatchQueue("stageQueue");
public static volatile DispatchQueue globalQueue = new DispatchQueue("globalQueue");
public static volatile DispatchQueue searchQueue = new DispatchQueue("searchQueue");
public static volatile DispatchQueue photoBookQueue = new DispatchQueue("photoBookQueue");
public static int[] arrColors = {0xffee4928, 0xff41a903, 0xffe09602, 0xff0f94ed, 0xff8f3bf7, 0xfffc4380, 0xff00a1c4, 0xffeb7002};
public static int[] arrUsersAvatars = {
......@@ -153,7 +156,7 @@ public class Utilities {
public native static long doPQNative(long _what);
public native static byte[] aesIgeEncryption(byte[] _what, byte[] _key, byte[] _iv, boolean encrypt, boolean changeIv, int len);
public native static void aesIgeEncryption2(ByteBuffer _what, byte[] _key, byte[] _iv, boolean encrypt, boolean changeIv, int len);
public native static void loadBitmap(String path, Bitmap bitmap, int scale);
public native static void loadBitmap(String path, int[] bitmap, int scale, int format, int width, int height);
public static void lockOrientation(Activity activity) {
if (prevOrientation != -10) {
......@@ -164,19 +167,47 @@ public class Utilities {
WindowManager manager = (WindowManager)activity.getSystemService(Activity.WINDOW_SERVICE);
if (manager != null && manager.getDefaultDisplay() != null) {
int rotation = manager.getDefaultDisplay().getRotation();
int orientation = activity.getResources().getConfiguration().orientation;
if (rotation == Surface.ROTATION_270) {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
} else if (rotation == Surface.ROTATION_90) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} else if (rotation == Surface.ROTATION_0) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
} else {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} else {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
}
......@@ -231,10 +262,17 @@ public class Utilities {
public static File getCacheDir() {
if (externalCacheNotAvailableState == 1 || externalCacheNotAvailableState == 0 && Environment.getExternalStorageState().startsWith(Environment.MEDIA_MOUNTED)) {
externalCacheNotAvailableState = 1;
return ApplicationLoader.applicationContext.getExternalCacheDir();
File file = ApplicationLoader.applicationContext.getExternalCacheDir();
if (file != null) {
return file;
}
}
externalCacheNotAvailableState = 2;
return ApplicationLoader.applicationContext.getCacheDir();
File file = ApplicationLoader.applicationContext.getCacheDir();
if (file != null) {
return file;
}
return new File("");
}
public static String bytesToHex(byte[] bytes) {
......@@ -668,7 +706,7 @@ public class Utilities {
try {
String str;
if (id >= 0) {
str = String.format(Locale.US, "%d%d", id, UserConfig.clientUserId);
str = String.format(Locale.US, "%d%d", id, UserConfig.getClientUserId());
} else {
str = String.format(Locale.US, "%d", id);
}
......@@ -707,6 +745,9 @@ public class Utilities {
}
public static String MD5(String md5) {
if (md5 == null) {
return null;
}
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes());
......@@ -949,7 +990,12 @@ public class Utilities {
}
public static void checkForCrashes(Activity context) {
CrashManager.register(context, BuildVars.HOCKEY_APP_HASH);
CrashManager.register(context, BuildVars.HOCKEY_APP_HASH, new CrashManagerListener() {
@Override
public boolean includeDeviceData() {
return true;
}
});
}
public static void checkForUpdates(Activity context) {
......@@ -957,4 +1003,8 @@ public class Utilities {
UpdateManager.register(context, BuildVars.HOCKEY_APP_HASH);
}
}
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
}
......@@ -107,7 +107,7 @@ public class MessageObject {
if (who != null && fromUser != null) {
if (isFromMe()) {
messageText = LocaleController.getString("ActionYouKickUser", R.string.ActionYouKickUser).replace("un2", Utilities.formatName(who.first_name, who.last_name));
} else if (message.action.user_id == UserConfig.clientUserId) {
} else if (message.action.user_id == UserConfig.getClientUserId()) {
messageText = LocaleController.getString("ActionKickUserYou", R.string.ActionKickUserYou).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
} else {
messageText = LocaleController.getString("ActionKickUser", R.string.ActionKickUser).replace("un2", Utilities.formatName(who.first_name, who.last_name)).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
......@@ -124,7 +124,7 @@ public class MessageObject {
if (whoUser != null && fromUser != null) {
if (isFromMe()) {
messageText = LocaleController.getString("ActionYouAddUser", R.string.ActionYouAddUser).replace("un2", Utilities.formatName(whoUser.first_name, whoUser.last_name));
} else if (message.action.user_id == UserConfig.clientUserId) {
} else if (message.action.user_id == UserConfig.getClientUserId()) {
messageText = LocaleController.getString("ActionAddUserYou", R.string.ActionAddUserYou).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
} else {
messageText = LocaleController.getString("ActionAddUser", R.string.ActionAddUser).replace("un2", Utilities.formatName(whoUser.first_name, whoUser.last_name)).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
......@@ -206,7 +206,7 @@ public class MessageObject {
}
} else if (message.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) {
String date = String.format("%s %s %s", LocaleController.formatterYear.format(((long)message.date) * 1000), LocaleController.getString("OtherAt", R.string.OtherAt), LocaleController.formatterDay.format(((long)message.date) * 1000));
messageText = LocaleController.formatString("NotificationUnrecognizedDevice", R.string.NotificationUnrecognizedDevice, UserConfig.currentUser.first_name, date, message.action.title, message.action.address);
messageText = LocaleController.formatString("NotificationUnrecognizedDevice", R.string.NotificationUnrecognizedDevice, UserConfig.getCurrentUser().first_name, date, message.action.title, message.action.address);
} else if (message.action instanceof TLRPC.TL_messageActionUserJoined) {
if (fromUser != null) {
messageText = LocaleController.formatString("NotificationContactJoined", R.string.NotificationContactJoined, Utilities.formatName(fromUser.first_name, fromUser.last_name));
......@@ -537,6 +537,6 @@ public class MessageObject {
}
public boolean isFromMe() {
return messageOwner.from_id == UserConfig.clientUserId;
return messageOwner.from_id == UserConfig.getClientUserId();
}
}
......@@ -8,6 +8,7 @@
package org.telegram.ui.Adapters;
import android.database.DataSetObserver;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
......@@ -38,4 +39,11 @@ public class BaseFragmentAdapter extends BaseAdapter {
public View getView(int i, View view, ViewGroup viewGroup) {
return null;
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer != null) {
super.unregisterDataSetObserver(observer);
}
}
}
......@@ -72,7 +72,7 @@ public class ContactsActivitySearchAdapter extends BaseFragmentAdapter {
public void run() {
final ArrayList<TLRPC.TL_contact> contactsCopy = new ArrayList<TLRPC.TL_contact>();
contactsCopy.addAll(ContactsController.getInstance().contacts);
Utilities.globalQueue.postRunnable(new Runnable() {
Utilities.searchQueue.postRunnable(new Runnable() {
@Override
public void run() {
String q = query.trim().toLowerCase();
......@@ -87,7 +87,7 @@ public class ContactsActivitySearchAdapter extends BaseFragmentAdapter {
for (TLRPC.TL_contact contact : contactsCopy) {
TLRPC.User user = MessagesController.getInstance().users.get(contact.user_id);
if (user.first_name != null && user.first_name.toLowerCase().startsWith(q) || user.last_name != null && user.last_name.toLowerCase().startsWith(q)) {
if (user.id == UserConfig.clientUserId) {
if (user.id == UserConfig.getClientUserId()) {
continue;
}
resultArrayNames.add(Utilities.generateSearchName(user.first_name, user.last_name, q));
......
......@@ -20,7 +20,7 @@ import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.PowerManager;
......@@ -29,7 +29,6 @@ import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.NotificationsService;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.ConnectionsManager;
......@@ -41,7 +40,6 @@ import org.telegram.messenger.ScreenReceiver;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;
public class ApplicationLoader extends Application {
......@@ -52,12 +50,12 @@ public class ApplicationLoader extends Application {
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static long lastPauseTime;
public static Bitmap cachedWallpaper = null;
public static Drawable cachedWallpaper = null;
public static volatile Context applicationContext = null;
public static volatile Handler applicationHandler = null;
private static volatile boolean applicationInited = false;
public static volatile boolean isScreenOn = false;
public static void postInitApplication() {
......@@ -93,7 +91,7 @@ public class ApplicationLoader extends Application {
}
UserConfig.loadConfig();
if (UserConfig.currentUser != null) {
if (UserConfig.getCurrentUser() != null) {
boolean changed = false;
SharedPreferences preferences = applicationContext.getSharedPreferences("Notifications", MODE_PRIVATE);
int v = preferences.getInt("v", 0);
......@@ -122,8 +120,8 @@ public class ApplicationLoader extends Application {
editor.commit();
}
MessagesController.getInstance().users.put(UserConfig.clientUserId, UserConfig.currentUser);
ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.currentUser.phone);
MessagesController.getInstance().users.put(UserConfig.getClientUserId(), UserConfig.getCurrentUser());
ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.getCurrentUser().phone);
ConnectionsManager.getInstance().initPushConnection();
}
......@@ -135,7 +133,6 @@ public class ApplicationLoader extends Application {
@Override
public void onCreate() {
super.onCreate();
lastPauseTime = System.currentTimeMillis();
applicationContext = getApplicationContext();
applicationHandler = new Handler(applicationContext.getMainLooper());
......@@ -153,10 +150,14 @@ public class ApplicationLoader extends Application {
applicationContext.startService(new Intent(applicationContext, NotificationsService.class));
if (android.os.Build.VERSION.SDK_INT >= 19) {
Calendar cal = Calendar.getInstance();
// Calendar cal = Calendar.getInstance();
// PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0);
// AlarmManager alarm = (AlarmManager) applicationContext.getSystemService(Context.ALARM_SERVICE);
// alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30000, pintent);
PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0);
AlarmManager alarm = (AlarmManager) applicationContext.getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30000, pintent);
AlarmManager alarm = (AlarmManager)applicationContext.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pintent);
}
} else {
stopPushService();
......@@ -182,14 +183,6 @@ public class ApplicationLoader extends Application {
}
}
public static void resetLastPauseTime() {
if (lastPauseTime != 0 && System.currentTimeMillis() - lastPauseTime > 5000) {
ContactsController.getInstance().checkContacts();
}
lastPauseTime = 0;
ConnectionsManager.getInstance().applicationMovedToForeground();
}
private void initPlayServices() {
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
......@@ -294,12 +287,14 @@ public class ApplicationLoader extends Application {
UserConfig.pushString = regid;
UserConfig.registeredForPush = !isNew;
UserConfig.saveConfig(false);
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
MessagesController.getInstance().registerForPush(regid);
}
});
if (UserConfig.getClientUserId() != 0) {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
MessagesController.getInstance().registerForPush(regid);
}
});
}
}
});
}
......
......@@ -233,7 +233,7 @@ public class ChatBaseCell extends BaseCell {
newUser = MessagesController.getInstance().users.get(currentMessageObject.messageOwner.fwd_from_id);
newNameString = null;
if (drawForwardedName && currentMessageObject.messageOwner instanceof TLRPC.TL_messageForwarded) {
if (newUser != null && drawForwardedName && currentMessageObject.messageOwner instanceof TLRPC.TL_messageForwarded) {
newNameString = Utilities.formatName(newUser.first_name, newUser.last_name);
}
return currentForwardNameString == null && newNameString != null || currentForwardNameString != null && newNameString == null || currentForwardNameString != null && newNameString != null && !currentForwardNameString.equals(newNameString);
......
......@@ -16,7 +16,6 @@ import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.View;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.LocaleController;
......@@ -28,8 +27,6 @@ import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Views.ImageReceiver;
import java.lang.ref.WeakReference;
public class ChatOrUserCell extends BaseCell {
private static TextPaint namePaint;
private static TextPaint nameEncryptedPaint;
......@@ -347,7 +344,7 @@ public class ChatOrUserCell extends BaseCell {
onlineString = subLabel;
} else {
onlineString = LocaleController.formatUserStatus(user);
if (user != null && (user.id == UserConfig.clientUserId || user.status != null && user.status.expires > ConnectionsManager.getInstance().getCurrentTime())) {
if (user != null && (user.id == UserConfig.getClientUserId() || user.status != null && user.status.expires > ConnectionsManager.getInstance().getCurrentTime())) {
currentOnlinePaint = onlinePaint;
onlineString = LocaleController.getString("Online", R.string.Online);
}
......
......@@ -423,7 +423,7 @@ public class DialogCell extends BaseCell {
} else if (encryptedChat instanceof TLRPC.TL_encryptedChatDiscarded) {
messageString = LocaleController.getString("EncryptionRejected", R.string.EncryptionRejected);
} else if (encryptedChat instanceof TLRPC.TL_encryptedChat) {
if (encryptedChat.admin_id == UserConfig.clientUserId) {
if (encryptedChat.admin_id == UserConfig.getClientUserId()) {
if (user != null && user.first_name != null) {
messageString = LocaleController.formatString("EncryptedChatStartedOutgoing", R.string.EncryptedChatStartedOutgoing, user.first_name);
} else {
......@@ -546,8 +546,8 @@ public class DialogCell extends BaseCell {
if (chat != null) {
nameString = chat.title;
} else if (user != null) {
if (user.id / 1000 != 333 && ContactsController.getInstance().contactsDict.get(user.id) == null) {
if (ContactsController.getInstance().contactsDict.size() == 0 && (!ContactsController.getInstance().contactsLoaded || ContactsController.getInstance().loadingContacts)) {
if (user.id / 1000 != 777 && user.id / 1000 != 333 && ContactsController.getInstance().contactsDict.get(user.id) == null) {
if (ContactsController.getInstance().contactsDict.size() == 0 && (!ContactsController.getInstance().contactsLoaded || ContactsController.getInstance().isLoadingContacts())) {
nameString = Utilities.formatName(user.first_name, user.last_name);
} else {
if (user.phone != null && user.phone.length() != 0) {
......
......@@ -102,6 +102,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent
onlineText = (TextView)fragmentView.findViewById(R.id.settings_online);
avatarImage = (BackupImageView)fragmentView.findViewById(R.id.settings_avatar_image);
avatarImage.processDetach = false;
phoneText = (TextView)fragmentView.findViewById(R.id.settings_name);
Typeface typeface = Utilities.getTypeface("fonts/rmedium.ttf");
phoneText.setTypeface(typeface);
......
......@@ -146,6 +146,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
searchWas = false;
ViewGroup group = (ViewGroup) listView.getParent();
listView.setAdapter(listViewAdapter);
listViewAdapter.notifyDataSetChanged();
if (!LocaleController.isRTL) {
listView.setPadding(Utilities.dp(16), listView.getPaddingTop(), Utilities.dp(30), listView.getPaddingBottom());
} else {
......@@ -171,6 +172,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
if (listView != null) {
listView.setPadding(Utilities.dp(16), listView.getPaddingTop(), Utilities.dp(16), listView.getPaddingBottom());
listView.setAdapter(searchListViewAdapter);
searchListViewAdapter.notifyDataSetChanged();
if(android.os.Build.VERSION.SDK_INT >= 11) {
listView.setFastScrollAlwaysVisible(false);
}
......@@ -205,7 +207,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (searching && searchWas) {
TLRPC.User user = searchListViewAdapter.getItem(i);
if (user == null || user.id == UserConfig.clientUserId) {
if (user == null || user.id == UserConfig.getClientUserId()) {
return;
}
if (returnAsResult) {
......@@ -263,7 +265,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
}
if (user != null) {
if (user.id == UserConfig.clientUserId) {
if (user.id == UserConfig.getClientUserId()) {
return;
}
if (returnAsResult) {
......@@ -288,7 +290,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
if (!contact.phones.isEmpty()) {
usePhone = contact.phones.get(0);
}
if (usePhone == null) {
if (usePhone == null || getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
......@@ -337,6 +339,9 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
private void didSelectResult(final TLRPC.User user, boolean useAlert) {
if (useAlert && selectAlertString != null) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.formatStringSimple(selectAlertString, Utilities.formatName(user.first_name, user.last_name)));
......
......@@ -22,6 +22,7 @@ import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Views.ActionBar.ActionBarLayer;
import org.telegram.ui.Views.ActionBar.ActionBarMenu;
import org.telegram.ui.Views.ActionBar.ActionBarMenuItem;
......@@ -85,7 +86,7 @@ public class CountrySelectActivity extends BaseFragment {
}
arr.add(c);
}
reader.close();//TODO
reader.close();
stream.close();
} catch (Exception e) {
FileLog.e("tmessages", e);
......@@ -280,7 +281,7 @@ public class CountrySelectActivity extends BaseFragment {
}
private void processSearch(final String query) {
Utilities.globalQueue.postRunnable(new Runnable() {
Utilities.searchQueue.postRunnable(new Runnable() {
@Override
public void run() {
......@@ -321,7 +322,7 @@ public class CountrySelectActivity extends BaseFragment {
});
}
private class SearchAdapter extends BaseAdapter {
private class SearchAdapter extends BaseFragmentAdapter {
private Context mContext;
public SearchAdapter(Context context) {
......
......@@ -20,7 +20,6 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
......@@ -28,7 +27,10 @@ import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Views.ActionBar.ActionBarLayer;
import org.telegram.ui.Views.ActionBar.ActionBarMenu;
import org.telegram.ui.Views.ActionBar.ActionBarMenuItem;
import org.telegram.ui.Views.BackupImageView;
import org.telegram.ui.Views.ActionBar.BaseFragment;
......@@ -43,7 +45,8 @@ import java.util.HashMap;
public class DocumentSelectActivity extends BaseFragment {
public static abstract interface DocumentSelectActivityDelegate {
public void didSelectFile(DocumentSelectActivity activity, String path, String name, String ext, long size);
public void didSelectFile(DocumentSelectActivity activity, String path);
public void startDocumentSelectActivity();
}
private ListView listView;
......@@ -134,9 +137,16 @@ public class DocumentSelectActivity extends BaseFragment {
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
} else if (id == 1) {
if (delegate != null) {
delegate.startDocumentSelectActivity();
}
finishFragment(false);
}
}
});
ActionBarMenu menu = actionBarLayer.createMenu();
ActionBarMenuItem item = menu.addItem(1, R.drawable.ic_ab_other);
fragmentView = inflater.inflate(R.layout.document_select_layout, container, false);
listAdapter = new ListAdapter(getParentActivity());
......@@ -176,7 +186,7 @@ public class DocumentSelectActivity extends BaseFragment {
return;
}
if (delegate != null) {
delegate.didSelectFile(DocumentSelectActivity.this, file.getAbsolutePath(), item.title, item.ext, file.length());
delegate.didSelectFile(DocumentSelectActivity.this, file.getAbsolutePath());
}
}
}
......@@ -290,7 +300,10 @@ public class DocumentSelectActivity extends BaseFragment {
return true;
}
private void showErrorBox(String error){
private void showErrorBox(String error) {
if (getParentActivity() == null) {
return;
}
new AlertDialog.Builder(getParentActivity())
.setTitle(LocaleController.getString("AppName", R.string.AppName))
.setMessage(error)
......@@ -374,7 +387,7 @@ public class DocumentSelectActivity extends BaseFragment {
return LocaleController.formatString("FreeOfTotal", R.string.FreeOfTotal, Utilities.formatFileSize(free), Utilities.formatFileSize(total));
}
private class ListAdapter extends BaseAdapter {
private class ListAdapter extends BaseFragmentAdapter {
private Context mContext;
public ListAdapter(Context context) {
......
......@@ -382,7 +382,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
public void run() {
final ArrayList<TLRPC.TL_contact> contactsCopy = new ArrayList<TLRPC.TL_contact>();
contactsCopy.addAll(ContactsController.getInstance().contacts);
Utilities.globalQueue.postRunnable(new Runnable() {
Utilities.searchQueue.postRunnable(new Runnable() {
@Override
public void run() {
if (query.length() == 0) {
......@@ -397,7 +397,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
for (TLRPC.TL_contact contact : contactsCopy) {
TLRPC.User user = MessagesController.getInstance().users.get(contact.user_id);
if (user.first_name.toLowerCase().startsWith(q) || user.last_name.toLowerCase().startsWith(q)) {
if (user.id == UserConfig.clientUserId) {
if (user.id == UserConfig.getClientUserId()) {
continue;
}
resultArrayNames.add(Utilities.generateSearchName(user.first_name, user.last_name, q));
......
......@@ -176,7 +176,9 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
CharSequence[] items;
......@@ -206,6 +208,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
});
avatarImage = (BackupImageView)fragmentView.findViewById(R.id.settings_avatar_image);
avatarImage.setImageResource(R.drawable.group_blue);
nameTextView = (EditText)fragmentView.findViewById(R.id.bubble_input_text);
nameTextView.setHint(LocaleController.getString("EnterGroupNamePlaceholder", R.string.EnterGroupNamePlaceholder));
......@@ -302,7 +305,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
}
Bundle args2 = new Bundle();
args2.putInt("chat_id", (Integer)args[0]);
presentFragment(new ChatActivity(args2));
presentFragment(new ChatActivity(args2), true);
}
});
}
......
......@@ -100,6 +100,9 @@ public class PhotoCropActivity extends BaseFragment {
} else {
draggingState = 0;
}
if (draggingState != 0) {
PhotoCropView.this.requestDisallowInterceptTouchEvent(true);
}
oldX = x;
oldY = y;
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment