Commit a21494ad authored by DrKLO's avatar DrKLO

Update to 1.3.26

Applied patch from https://github.com/DrKLO/Telegram/pull/99 . Thanks.
Added German localization. Thanks to all from
https://github.com/DrKLO/Telegram/pull/129
Experimental audio (will not go to market yet, we will switch to opus
codec)
Improved text drawing perfomance (now Telegram can draw even «War and
Peace» in one message)
Ability to send multiple photos and documents from external apps
Contacts fixes
Memory usage optimizations in network code (receiving data)
Partly switched to native ByteBuffers (decoding received data)
Added support of Telegram API Layer 12
Bug fixes
parent 9aeb8be8
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
#include "aes.h" #include "aes.h"
#include "log.h" #include "log.h"
JNIEXPORT jbyteArray Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIEnv *env, jclass class, jbyteArray _what, jbyteArray _key, jbyteArray _iv, jboolean encrypt, jboolean changeIv) { JNIEXPORT jbyteArray Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIEnv *env, jclass class, jbyteArray _what, jbyteArray _key, jbyteArray _iv, jboolean encrypt, jboolean changeIv, jint l) {
unsigned char *what = (unsigned char *)(*env)->GetByteArrayElements(env, _what, NULL); unsigned char *what = (unsigned char *)(*env)->GetByteArrayElements(env, _what, NULL);
unsigned char *key = (unsigned char *)(*env)->GetByteArrayElements(env, _key, NULL); unsigned char *key = (unsigned char *)(*env)->GetByteArrayElements(env, _key, NULL);
unsigned char *__iv = (unsigned char *)(*env)->GetByteArrayElements(env, _iv, NULL); unsigned char *__iv = (unsigned char *)(*env)->GetByteArrayElements(env, _iv, NULL);
...@@ -20,7 +20,7 @@ JNIEXPORT jbyteArray Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIE ...@@ -20,7 +20,7 @@ JNIEXPORT jbyteArray Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIE
iv = __iv; iv = __iv;
} }
int len = (*env)->GetArrayLength(env, _what); int len = l == 0 ? (*env)->GetArrayLength(env, _what) : l;
AES_KEY akey; AES_KEY akey;
if (!encrypt) { if (!encrypt) {
AES_set_decrypt_key(key, (*env)->GetArrayLength(env, _key) * 8, &akey); AES_set_decrypt_key(key, (*env)->GetArrayLength(env, _key) * 8, &akey);
...@@ -40,6 +40,36 @@ JNIEXPORT jbyteArray Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIE ...@@ -40,6 +40,36 @@ JNIEXPORT jbyteArray Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIE
return _what; return _what;
} }
JNIEXPORT void Java_org_telegram_messenger_Utilities_aesIgeEncryption2(JNIEnv *env, jclass class, jobject _what, jbyteArray _key, jbyteArray _iv, jboolean encrypt, jboolean changeIv, jint l) {
jbyte *what = (*env)->GetDirectBufferAddress(env, _what);
unsigned char *key = (unsigned char *)(*env)->GetByteArrayElements(env, _key, NULL);
unsigned char *__iv = (unsigned char *)(*env)->GetByteArrayElements(env, _iv, NULL);
unsigned char *iv = 0;
if (!changeIv) {
iv = (unsigned char *)malloc((*env)->GetArrayLength(env, _iv));
memcpy(iv, __iv, (*env)->GetArrayLength(env, _iv));
} else {
iv = __iv;
}
AES_KEY akey;
if (!encrypt) {
AES_set_decrypt_key(key, (*env)->GetArrayLength(env, _key) * 8, &akey);
AES_ige_encrypt(what, what, l, &akey, iv, AES_DECRYPT);
} else {
AES_set_encrypt_key(key, (*env)->GetArrayLength(env, _key) * 8, &akey);
AES_ige_encrypt(what, what, l, &akey, iv, AES_ENCRYPT);
}
(*env)->ReleaseByteArrayElements(env, _key, key, JNI_ABORT);
if (!changeIv) {
(*env)->ReleaseByteArrayElements(env, _iv, __iv, JNI_ABORT);
free(iv);
} else {
(*env)->ReleaseByteArrayElements(env, _iv, __iv, 0);
}
}
uint64_t gcd(uint64_t a, uint64_t b){ uint64_t gcd(uint64_t a, uint64_t b){
while(a != 0 && b != 0) { while(a != 0 && b != 0) {
while((b & 1) == 0) b >>= 1; while((b & 1) == 0) b >>= 1;
......
This diff is collapsed.
This diff is collapsed.
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.telegram.messenger" package="org.telegram.messenger"
android:versionCode="160" android:versionCode="175"
android:versionName="1.3.21"> android:versionName="1.3.26">
<supports-screens android:anyDensity="true" <supports-screens android:anyDensity="true"
android:smallScreens="true" android:smallScreens="true"
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
<uses-feature android:name="android.hardware.screen.PORTRAIT" android:required="false" /> <uses-feature android:name="android.hardware.screen.PORTRAIT" android:required="false" />
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<!--<uses-permission android:name="android.permission.RECORD_AUDIO" />--> <uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.RECEIVE_SMS" />
...@@ -55,7 +55,7 @@ ...@@ -55,7 +55,7 @@
<permission android:name="org.telegram.messenger.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <permission android:name="org.telegram.messenger.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<application <application
android:allowBackup="true" android:allowBackup="false"
android:icon="@drawable/ic_launcher" android:icon="@drawable/ic_launcher"
android:label="@string/AppName" android:label="@string/AppName"
android:theme="@style/Theme.TMessages.Start" android:theme="@style/Theme.TMessages.Start"
...@@ -84,11 +84,26 @@ ...@@ -84,11 +84,26 @@
<category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="video/*"/> <data android:mimeType="video/*"/>
</intent-filter> </intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*"/>
</intent-filter>
<intent-filter> <intent-filter>
<action android:name="android.intent.action.SEND"/> <action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/> <data android:mimeType="text/plain"/>
</intent-filter> </intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="*/*"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="*/*"/>
</intent-filter>
<intent-filter> <intent-filter>
<action android:name="android.intent.action.VIEW"/> <action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.DEFAULT"/>
...@@ -165,9 +180,6 @@ ...@@ -165,9 +180,6 @@
<meta-data android:name="android.provider.CONTACTS_STRUCTURE" <meta-data android:name="android.provider.CONTACTS_STRUCTURE"
android:resource="@xml/contacts" /> android:resource="@xml/contacts" />
</service> </service>
<service android:name="org.telegram.messenger.GcmService" android:enabled="true" android:exported="true"/>
<service android:name=".BackgroundService" android:enabled="true" android:stopWithTask="false"/>
<uses-library android:name="com.google.android.maps" android:required="false"/> <uses-library android:name="com.google.android.maps" android:required="false"/>
</application> </application>
......
...@@ -22,8 +22,6 @@ import java.nio.ByteBuffer; ...@@ -22,8 +22,6 @@ import java.nio.ByteBuffer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import jawnae.pyronet.PyroException;
public class ByteStream { public class ByteStream {
private final List<ByteBuffer> queue; private final List<ByteBuffer> queue;
...@@ -51,9 +49,11 @@ public class ByteStream { ...@@ -51,9 +49,11 @@ public class ByteStream {
public boolean hasData() { public boolean hasData() {
int size = this.queue.size(); int size = this.queue.size();
for (int i = 0; i < size; i++) for (ByteBuffer aQueue : this.queue) {
if (this.queue.get(i).hasRemaining()) if (aQueue.hasRemaining()) {
return true; return true;
}
}
return false; return false;
} }
...@@ -61,8 +61,9 @@ public class ByteStream { ...@@ -61,8 +61,9 @@ public class ByteStream {
int size = this.queue.size(); int size = this.queue.size();
int sum = 0; int sum = 0;
for (int i = 0; i < size; i++) for (ByteBuffer aQueue : this.queue) {
sum += this.queue.get(i).remaining(); sum += aQueue.remaining();
}
return sum; return sum;
} }
......
...@@ -107,6 +107,7 @@ public class PyroClient { ...@@ -107,6 +107,7 @@ public class PyroClient {
* set * set
*/ */
@SuppressWarnings("unchecked")
public <T> T attachment() { public <T> T attachment() {
return (T) this.attachment; return (T) this.attachment;
} }
...@@ -155,12 +156,6 @@ public class PyroClient { ...@@ -155,12 +156,6 @@ public class PyroClient {
((SocketChannel) key.channel()).socket().setKeepAlive(enabled); ((SocketChannel) key.channel()).socket().setKeepAlive(enabled);
} }
//
//
//
private boolean doEagerWrite = false; private boolean doEagerWrite = false;
/** /**
...@@ -320,7 +315,7 @@ public class PyroClient { ...@@ -320,7 +315,7 @@ public class PyroClient {
public void run() { public void run() {
try { try {
if (key.channel().isOpen()) { if (key.channel().isOpen()) {
((SocketChannel) key.channel()).close(); (key.channel()).close();
} }
} catch (Exception exc) { } catch (Exception exc) {
selector().scheduleTask(this); selector().scheduleTask(this);
...@@ -340,7 +335,7 @@ public class PyroClient { ...@@ -340,7 +335,7 @@ public class PyroClient {
public boolean isDisconnected() { public boolean isDisconnected() {
this.selector.checkThread(); this.selector.checkThread();
return !((SocketChannel) this.key.channel()).isOpen(); return !this.key.channel().isOpen();
} }
// //
...@@ -368,9 +363,7 @@ public class PyroClient { ...@@ -368,9 +363,7 @@ public class PyroClient {
private long lastEventTime; private long lastEventTime;
boolean didTimeout(long now) { boolean didTimeout(long now) {
if (this.timeout == 0) return this.timeout != 0 && (now - this.lastEventTime) > this.timeout;
return false; // never timeout
return (now - this.lastEventTime) > this.timeout;
} }
private void onReadyToConnect(long now) throws IOException { private void onReadyToConnect(long now) throws IOException {
...@@ -442,7 +435,7 @@ public class PyroClient { ...@@ -442,7 +435,7 @@ public class PyroClient {
try { try {
// if the key is invalid, the channel may remain open!! // if the key is invalid, the channel may remain open!!
((SocketChannel) this.key.channel()).close(); this.key.channel().close();
} catch (Exception exc) { } catch (Exception exc) {
// type: java.io.IOException // type: java.io.IOException
// message: // message:
...@@ -488,7 +481,7 @@ public class PyroClient { ...@@ -488,7 +481,7 @@ public class PyroClient {
+ "]"; + "]";
} }
private final String getAddressText() { private String getAddressText() {
if (!this.key.channel().isOpen()) if (!this.key.channel().isOpen())
return "closed"; return "closed";
...@@ -510,7 +503,7 @@ public class PyroClient { ...@@ -510,7 +503,7 @@ public class PyroClient {
interested); interested);
} }
static final SelectionKey bindAndConfigure(PyroSelector selector, static SelectionKey bindAndConfigure(PyroSelector selector,
SocketChannel channel, InetSocketAddress bind) throws IOException { SocketChannel channel, InetSocketAddress bind) throws IOException {
selector.checkThread(); selector.checkThread();
...@@ -519,7 +512,7 @@ public class PyroClient { ...@@ -519,7 +512,7 @@ public class PyroClient {
return configure(selector, channel, true); return configure(selector, channel, true);
} }
static final SelectionKey configure(PyroSelector selector, static SelectionKey configure(PyroSelector selector,
SocketChannel channel, boolean connect) throws IOException { SocketChannel channel, boolean connect) throws IOException {
selector.checkThread(); selector.checkThread();
......
...@@ -18,6 +18,9 @@ ...@@ -18,6 +18,9 @@
package jawnae.pyronet; package jawnae.pyronet;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
...@@ -27,13 +30,16 @@ public class PyroClientAdapter implements PyroClientListener { ...@@ -27,13 +30,16 @@ public class PyroClientAdapter implements PyroClientListener {
} }
public void unconnectableClient(PyroClient client, Exception cause) { public void unconnectableClient(PyroClient client, Exception cause) {
System.out.println("unconnectable"); if (ConnectionsManager.DEBUG_VERSION) {
FileLog.e("tmessages", "unconnectable");
}
} }
public void droppedClient(PyroClient client, IOException cause) { public void droppedClient(PyroClient client, IOException cause) {
if (cause != null) { if (cause != null) {
System.out.println(this.getClass().getSimpleName() if (ConnectionsManager.DEBUG_VERSION) {
+ ".droppedClient() caught exception: " + cause); FileLog.e("tmessages", this.getClass().getSimpleName() + ".droppedClient() caught exception: " + cause);
}
} }
} }
......
...@@ -21,8 +21,6 @@ package jawnae.pyronet; ...@@ -21,8 +21,6 @@ package jawnae.pyronet;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import jawnae.pyronet.PyroClient;
public interface PyroClientListener { public interface PyroClientListener {
public void connectedClient(PyroClient client); public void connectedClient(PyroClient client);
......
...@@ -75,14 +75,8 @@ public class PyroSelector { ...@@ -75,14 +75,8 @@ public class PyroSelector {
return copy; return copy;
} }
//
public final boolean isNetworkThread() { public final boolean isNetworkThread() {
if (DO_NOT_CHECK_NETWORK_THREAD) { return DO_NOT_CHECK_NETWORK_THREAD || networkThread == Thread.currentThread();
return true;
}
return networkThread == Thread.currentThread();
} }
public final Thread networkThread() { public final Thread networkThread() {
...@@ -95,8 +89,7 @@ public class PyroSelector { ...@@ -95,8 +89,7 @@ public class PyroSelector {
} }
if (!this.isNetworkThread()) { if (!this.isNetworkThread()) {
throw new PyroException( throw new PyroException("call from outside the network-thread, you must schedule tasks");
"call from outside the network-thread, you must schedule tasks");
} }
} }
...@@ -104,13 +97,8 @@ public class PyroSelector { ...@@ -104,13 +97,8 @@ public class PyroSelector {
return this.connect(host, null); return this.connect(host, null);
} }
public PyroClient connect(InetSocketAddress host, InetSocketAddress bind) public PyroClient connect(InetSocketAddress host, InetSocketAddress bind) throws IOException {
throws IOException { return new PyroClient(this, bind, host);
try {
return new PyroClient(this, bind, host);
} catch (IOException exc) {
throw exc;
}
} }
public void select() { public void select() {
...@@ -144,17 +132,16 @@ public class PyroSelector { ...@@ -144,17 +132,16 @@ public class PyroSelector {
} }
} }
private final void performNioSelect(long timeout) { private void performNioSelect(long timeout) {
int selected; int selected;
try { try {
selected = nioSelector.select(timeout); selected = nioSelector.select(timeout);
} catch (IOException exc) { } catch (IOException exc) {
exc.printStackTrace(); exc.printStackTrace();
return;
} }
} }
private final void handleSelectedKeys(long now) { private void handleSelectedKeys(long now) {
Iterator<SelectionKey> keys = nioSelector.selectedKeys().iterator(); Iterator<SelectionKey> keys = nioSelector.selectedKeys().iterator();
while (keys.hasNext()) { while (keys.hasNext()) {
...@@ -168,7 +155,7 @@ public class PyroSelector { ...@@ -168,7 +155,7 @@ public class PyroSelector {
} }
} }
private final void handleSocketTimeouts(long now) { private void handleSocketTimeouts(long now) {
for (SelectionKey key: nioSelector.keys()) { for (SelectionKey key: nioSelector.keys()) {
if (key.channel() instanceof SocketChannel) { if (key.channel() instanceof SocketChannel) {
PyroClient client = (PyroClient) key.attachment(); PyroClient client = (PyroClient) key.attachment();
......
...@@ -58,9 +58,12 @@ public class PhoneFormat { ...@@ -58,9 +58,12 @@ public class PhoneFormat {
return res.toString(); return res.toString();
} }
public static String stripExceptNumbers(String str) { public static String stripExceptNumbers(String str, boolean includePlus) {
StringBuilder res = new StringBuilder(str); StringBuilder res = new StringBuilder(str);
String phoneChars = "0123456789"; String phoneChars = "0123456789";
if (includePlus) {
phoneChars += "+";
}
for (int i = res.length() - 1; i >= 0; i--) { for (int i = res.length() - 1; i >= 0; i--) {
if (!phoneChars.contains(res.substring(i, i + 1))) { if (!phoneChars.contains(res.substring(i, i + 1))) {
res.deleteCharAt(i); res.deleteCharAt(i);
...@@ -69,6 +72,10 @@ public class PhoneFormat { ...@@ -69,6 +72,10 @@ public class PhoneFormat {
return res.toString(); return res.toString();
} }
public static String stripExceptNumbers(String str) {
return stripExceptNumbers(str, false);
}
public PhoneFormat() { public PhoneFormat() {
init(null); init(null);
} }
......
/*
* This is the source code of Telegram for Android v. 1.3.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-2014.
*/
package org.telegram.messenger;
public abstract class AbsSerializedData {
public abstract void writeInt32(int x);
public abstract void writeInt64(long x);
public abstract void writeBool(boolean value);
public abstract void writeRaw(byte[] b);
public abstract void writeRaw(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 int readInt32();
public abstract int readInt32(boolean[] error);
public abstract boolean readBool();
public abstract long readInt64();
public abstract long readInt64(boolean[] error);
public abstract void readRaw(byte[] b);
public abstract byte[] readData(int count);
public abstract String readString();
public abstract byte[] readByteArray();
public abstract ByteBufferDesc readByteBuffer();
public abstract double readDouble();
public abstract int length();
}
/*
* This is the source code of Telegram for Android v. 1.3.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.
*/
package org.telegram.messenger;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
public class BackgroundService extends Service {
private Handler handler = new Handler(Looper.getMainLooper());
private Runnable checkRunnable = new Runnable() {
@Override
public void run() {
check();
}
};
public BackgroundService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
check();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.e("tmessages", "onStartCommand");
return START_STICKY;
}
private void check() {
handler.removeCallbacks(checkRunnable);
handler.postDelayed(checkRunnable, 1500);
ConnectionsManager connectionsManager = ConnectionsManager.Instance;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("tmessages", "onDestroy");
}
}
/*
* This is the source code of Telegram for Android v. 1.3.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-2014.
*/
package org.telegram.messenger;
import java.util.concurrent.ConcurrentLinkedQueue;
public class BuffersStorage {
public static BuffersStorage Instance = new BuffersStorage();
private final ConcurrentLinkedQueue<ByteBufferDesc> freeBuffers128;
private final ConcurrentLinkedQueue<ByteBufferDesc> freeBuffers1024;
private final ConcurrentLinkedQueue<ByteBufferDesc> freeBuffers4096;
private final ConcurrentLinkedQueue<ByteBufferDesc> freeBuffers16384;
private final ConcurrentLinkedQueue<ByteBufferDesc> freeBuffers32768;
public BuffersStorage() {
freeBuffers128 = new ConcurrentLinkedQueue<ByteBufferDesc>();
freeBuffers1024 = new ConcurrentLinkedQueue<ByteBufferDesc>();
freeBuffers4096 = new ConcurrentLinkedQueue<ByteBufferDesc>();
freeBuffers16384 = new ConcurrentLinkedQueue<ByteBufferDesc>();
freeBuffers32768 = new ConcurrentLinkedQueue<ByteBufferDesc>();
for (int a = 0; a < 5; a++) {
freeBuffers128.add(new ByteBufferDesc(128));
}
for (int a = 0; a < 5; a++) {
freeBuffers1024.add(new ByteBufferDesc(1024 + 200));
}
for (int a = 0; a < 2; a++) {
freeBuffers4096.add(new ByteBufferDesc(4096 + 200));
}
for (int a = 0; a < 2; a++) {
freeBuffers16384.add(new ByteBufferDesc(16384 + 200));
}
for (int a = 0; a < 2; a++) {
freeBuffers32768.add(new ByteBufferDesc(40000));
}
}
public ByteBufferDesc getFreeBuffer(int size) {
ByteBufferDesc buffer = null;
if (size <= 128) {
synchronized (freeBuffers128) {
buffer = freeBuffers128.poll();
}
if (buffer == null) {
buffer = new ByteBufferDesc(128);
FileLog.e("tmessages", "create new 128 buffer");
}
} else if (size <= 1024 + 200) {
synchronized (freeBuffers1024) {
buffer = freeBuffers1024.poll();
}
if (buffer == null) {
buffer = new ByteBufferDesc(1024 + 200);
FileLog.e("tmessages", "create new 1024 buffer");
}
} else if (size <= 4096 + 200) {
synchronized (freeBuffers4096) {
buffer = freeBuffers4096.poll();
}
if (buffer == null) {
buffer = new ByteBufferDesc(4096 + 200);
FileLog.e("tmessages", "create new 4096 buffer");
}
} else if (size <= 16384 + 200) {
synchronized (freeBuffers16384) {
buffer = freeBuffers16384.poll();
}
if (buffer == null) {
buffer = new ByteBufferDesc(16384 + 200);
FileLog.e("tmessages", "create new 16384 buffer");
}
} else if (size <= 40000) {
synchronized (freeBuffers32768) {
buffer = freeBuffers32768.poll();
}
if (buffer == null) {
buffer = new ByteBufferDesc(40000);
FileLog.e("tmessages", "create new 40000 buffer");
}
} else {
buffer = new ByteBufferDesc(size);
}
buffer.buffer.limit(size).rewind();
return buffer;
}
public void reuseFreeBuffer(ByteBufferDesc buffer) {
if (buffer == null) {
return;
}
if (buffer.buffer.capacity() == 128) {
synchronized (freeBuffers128) {
if (freeBuffers128.contains(buffer)) {
throw new RuntimeException("already containing buffer! 0");
}
freeBuffers128.add(buffer);
}
} else if (buffer.buffer.capacity() == 1024 + 200) {
synchronized (freeBuffers1024) {
if (freeBuffers1024.contains(buffer)) {
throw new RuntimeException("already containing buffer! 1");
}
freeBuffers1024.add(buffer);
}
} else if (buffer.buffer.capacity() == 4096 + 200) {
synchronized (freeBuffers4096) {
if (freeBuffers4096.contains(buffer)) {
throw new RuntimeException("already containing buffer! 2");
}
freeBuffers4096.add(buffer);
}
} else if (buffer.buffer.capacity() == 16384 + 200) {
synchronized (freeBuffers16384) {
if (freeBuffers16384.contains(buffer)) {
throw new RuntimeException("already containing buffer! 3");
}
freeBuffers16384.add(buffer);
}
} else if (buffer.buffer.capacity() == 40000) {
synchronized (freeBuffers32768) {
if (freeBuffers32768.contains(buffer)) {
throw new RuntimeException("already containing buffer! 4");
}
freeBuffers32768.add(buffer);
}
}
}
}
...@@ -11,7 +11,6 @@ package org.telegram.messenger; ...@@ -11,7 +11,6 @@ package org.telegram.messenger;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import org.telegram.TL.TLRPC;
import org.telegram.ui.ApplicationLoader; import org.telegram.ui.ApplicationLoader;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -20,7 +19,7 @@ import java.util.Comparator; ...@@ -20,7 +19,7 @@ import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
public class Datacenter { public class Datacenter {
private final int DATA_VERSION = 3; private static final int DATA_VERSION = 4;
public int datacenterId; public int datacenterId;
public ArrayList<String> addresses = new ArrayList<String>(); public ArrayList<String> addresses = new ArrayList<String>();
...@@ -31,7 +30,7 @@ public class Datacenter { ...@@ -31,7 +30,7 @@ public class Datacenter {
public long authDownloadSessionId; public long authDownloadSessionId;
public long authUploadSessionId; public long authUploadSessionId;
public byte[] authKey; public byte[] authKey;
public byte[] authKeyId; public long authKeyId;
public int lastInitVersion = 0; public int lastInitVersion = 0;
private volatile int currentPortNum = 0; private volatile int currentPortNum = 0;
private volatile int currentAddressNum = 0; private volatile int currentAddressNum = 0;
...@@ -59,7 +58,7 @@ public class Datacenter { ...@@ -59,7 +58,7 @@ public class Datacenter {
} }
len = data.readInt32(); len = data.readInt32();
if (len != 0) { if (len != 0) {
authKeyId = data.readData(len); authKeyId = data.readInt64();
} }
authorized = data.readInt32() != 0; authorized = data.readInt32() != 0;
len = data.readInt32(); len = data.readInt32();
...@@ -75,9 +74,9 @@ public class Datacenter { ...@@ -75,9 +74,9 @@ public class Datacenter {
} }
} else if (version == 1) { } else if (version == 1) {
int currentVersion = data.readInt32(); int currentVersion = data.readInt32();
if (currentVersion == 2 || currentVersion == 3) { if (currentVersion == 2 || currentVersion == 3 || currentVersion == 4) {
datacenterId = data.readInt32(); datacenterId = data.readInt32();
if (currentVersion == 3) { if (currentVersion >= 3) {
lastInitVersion = data.readInt32(); lastInitVersion = data.readInt32();
} }
int len = data.readInt32(); int len = data.readInt32();
...@@ -91,9 +90,13 @@ public class Datacenter { ...@@ -91,9 +90,13 @@ public class Datacenter {
if (len != 0) { if (len != 0) {
authKey = data.readData(len); authKey = data.readData(len);
} }
len = data.readInt32(); if (currentVersion == 4) {
if (len != 0) { authKeyId = data.readInt64();
authKeyId = data.readData(len); } else {
len = data.readInt32();
if (len != 0) {
authKeyId = data.readInt64();
}
} }
authorized = data.readInt32() != 0; authorized = data.readInt32() != 0;
len = data.readInt32(); len = data.readInt32();
...@@ -108,6 +111,8 @@ public class Datacenter { ...@@ -108,6 +111,8 @@ public class Datacenter {
authServerSaltSet.add(salt); authServerSaltSet.add(salt);
} }
} }
} else if (version == 2) {
} }
readCurrentAddressAndPortNum(); readCurrentAddressAndPortNum();
} }
...@@ -198,12 +203,7 @@ public class Datacenter { ...@@ -198,12 +203,7 @@ public class Datacenter {
} else { } else {
stream.writeInt32(0); stream.writeInt32(0);
} }
if (authKeyId != null) { stream.writeInt64(authKeyId);
stream.writeInt32(authKeyId.length);
stream.writeRaw(authKeyId);
} else {
stream.writeInt32(0);
}
stream.writeInt32(authorized ? 1 : 0); stream.writeInt32(authorized ? 1 : 0);
stream.writeInt32(authServerSaltSet.size()); stream.writeInt32(authServerSaltSet.size());
for (ServerSalt salt : authServerSaltSet) { for (ServerSalt salt : authServerSaltSet) {
...@@ -215,7 +215,7 @@ public class Datacenter { ...@@ -215,7 +215,7 @@ public class Datacenter {
public void clear() { public void clear() {
authKey = null; authKey = null;
authKeyId = null; authKeyId = 0;
authorized = false; authorized = false;
authServerSaltSet.clear(); authServerSaltSet.clear();
} }
......
...@@ -8,9 +8,6 @@ ...@@ -8,9 +8,6 @@
package org.telegram.messenger; package org.telegram.messenger;
import org.telegram.TL.TLObject;
import org.telegram.TL.TLRPC;
import java.util.HashMap; import java.util.HashMap;
public class ExportAuthorizationAction extends Action { public class ExportAuthorizationAction extends Action {
......
...@@ -12,15 +12,13 @@ import android.graphics.Bitmap; ...@@ -12,15 +12,13 @@ import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.os.Build; import android.os.Build;
import org.telegram.TL.TLObject;
import org.telegram.TL.TLRPC;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
import java.net.URL; import java.net.URL;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.net.URLConnection; import java.net.URLConnection;
import java.nio.channels.FileChannel;
import java.util.Scanner; import java.util.Scanner;
public class FileLoadOperation { public class FileLoadOperation {
...@@ -238,14 +236,18 @@ public class FileLoadOperation { ...@@ -238,14 +236,18 @@ public class FileLoadOperation {
opts.inSampleSize = (int)scaleFactor; opts.inSampleSize = (int)scaleFactor;
} }
opts.inPreferredConfig = Bitmap.Config.ARGB_8888; if (filter == null) {
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
} else {
opts.inPreferredConfig = Bitmap.Config.RGB_565;
}
opts.inDither = false; opts.inDither = false;
image = BitmapFactory.decodeStream(is, null, opts); image = BitmapFactory.decodeStream(is, null, opts);
is.close(); is.close();
if (image == null) { if (image == null) {
//if (!dontDelete) { if (!dontDelete && cacheFileFinal.length() == 0) {
// cacheFileFinal.delete(); cacheFileFinal.delete();
//} }
} else { } else {
if (filter != null && image != null) { if (filter != null && image != null) {
float bitmapW = image.getWidth(); float bitmapW = image.getWidth();
...@@ -278,9 +280,9 @@ public class FileLoadOperation { ...@@ -278,9 +280,9 @@ public class FileLoadOperation {
} }
}); });
} catch (Exception e) { } catch (Exception e) {
//if (!dontDelete) { if (!dontDelete && cacheFileFinal.length() == 0) {
// cacheFileFinal.delete(); cacheFileFinal.delete();
//} }
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
} }
...@@ -436,7 +438,12 @@ public class FileLoadOperation { ...@@ -436,7 +438,12 @@ public class FileLoadOperation {
opts.inSampleSize = (int) scaleFactor; opts.inSampleSize = (int) scaleFactor;
} }
opts.inPreferredConfig = Bitmap.Config.ARGB_8888; if (filter == null) {
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
} else {
opts.inPreferredConfig = Bitmap.Config.RGB_565;
}
opts.inDither = false; opts.inDither = false;
try { try {
if (renamed) { if (renamed) {
...@@ -558,13 +565,13 @@ public class FileLoadOperation { ...@@ -558,13 +565,13 @@ public class FileLoadOperation {
} }
TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile(); TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile();
req.location = location; req.location = location;
if (totalBytesCount == -1) { //if (totalBytesCount == -1) {
req.offset = 0; // req.offset = 0;
req.limit = 0; // req.limit = 0;
} else { //} else {
req.offset = downloadedBytes; req.offset = downloadedBytes;
req.limit = downloadChunkSize; req.limit = downloadChunkSize;
} //}
requestToken = ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() { requestToken = ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override @Override
public void run(TLObject response, TLRPC.TL_error error) { public void run(TLObject response, TLRPC.TL_error error) {
...@@ -572,22 +579,22 @@ public class FileLoadOperation { ...@@ -572,22 +579,22 @@ public class FileLoadOperation {
if (error == null) { if (error == null) {
TLRPC.TL_upload_file res = (TLRPC.TL_upload_file)response; TLRPC.TL_upload_file res = (TLRPC.TL_upload_file)response;
try { try {
if (res.bytes.length == 0) { if (res.bytes.limit() == 0) {
onFinishLoadingFile(); onFinishLoadingFile();
return; return;
} }
if (key != null) { if (key != null) {
res.bytes = Utilities.aesIgeEncryption(res.bytes, key, iv, false, true); Utilities.aesIgeEncryption2(res.bytes.buffer, key, iv, false, true, res.bytes.limit());
} }
if (fileOutputStream != null) { if (fileOutputStream != null) {
fileOutputStream.write(res.bytes); FileChannel channel = fileOutputStream.getChannel();
channel.write(res.bytes.buffer);
} }
if (fiv != null) { if (fiv != null) {
fiv.seek(0); fiv.seek(0);
fiv.write(iv); fiv.write(iv);
} }
downloadedBytes += res.bytes.length; downloadedBytes += res.bytes.limit();
res.bytes = null;
if (totalBytesCount > 0) { if (totalBytesCount > 0) {
delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float)downloadedBytes / (float)totalBytesCount)); delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float)downloadedBytes / (float)totalBytesCount));
} }
......
...@@ -16,7 +16,6 @@ import android.graphics.Matrix; ...@@ -16,7 +16,6 @@ import android.graphics.Matrix;
import android.media.ExifInterface; import android.media.ExifInterface;
import android.os.Build; import android.os.Build;
import org.telegram.TL.TLRPC;
import org.telegram.objects.MessageObject; import org.telegram.objects.MessageObject;
import org.telegram.ui.ApplicationLoader; import org.telegram.ui.ApplicationLoader;
import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Views.BackupImageView;
...@@ -45,6 +44,7 @@ public class FileLoader { ...@@ -45,6 +44,7 @@ public class FileLoader {
private final int maxConcurentLoadingOpertaionsCount = 2; private final int maxConcurentLoadingOpertaionsCount = 2;
private Queue<FileUploadOperation> uploadOperationQueue; private Queue<FileUploadOperation> uploadOperationQueue;
private ConcurrentHashMap<String, FileUploadOperation> uploadOperationPaths; private ConcurrentHashMap<String, FileUploadOperation> uploadOperationPaths;
private ConcurrentHashMap<String, FileUploadOperation> uploadOperationPathsEnc;
private int currentUploadOperationsCount = 0; private int currentUploadOperationsCount = 0;
private Queue<FileLoadOperation> loadOperationQueue; private Queue<FileLoadOperation> loadOperationQueue;
private ConcurrentHashMap<String, FileLoadOperation> loadOperationPaths; private ConcurrentHashMap<String, FileLoadOperation> loadOperationPaths;
...@@ -294,18 +294,27 @@ public class FileLoader { ...@@ -294,18 +294,27 @@ public class FileLoader {
runningOperation = new LinkedList<FileLoadOperation>(); runningOperation = new LinkedList<FileLoadOperation>();
uploadOperationQueue = new LinkedList<FileUploadOperation>(); uploadOperationQueue = new LinkedList<FileUploadOperation>();
uploadOperationPaths = new ConcurrentHashMap<String, FileUploadOperation>(); uploadOperationPaths = new ConcurrentHashMap<String, FileUploadOperation>();
uploadOperationPathsEnc = new ConcurrentHashMap<String, FileUploadOperation>();
loadOperationPaths = new ConcurrentHashMap<String, FileLoadOperation>(); loadOperationPaths = new ConcurrentHashMap<String, FileLoadOperation>();
loadOperationQueue = new LinkedList<FileLoadOperation>(); loadOperationQueue = new LinkedList<FileLoadOperation>();
} }
public void cancelUploadFile(final String location) { public void cancelUploadFile(final String location, final boolean enc) {
Utilities.fileUploadQueue.postRunnable(new Runnable() { Utilities.fileUploadQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
FileUploadOperation operation = uploadOperationPaths.get(location); if (!enc) {
if (operation != null) { FileUploadOperation operation = uploadOperationPaths.get(location);
uploadOperationQueue.remove(operation); if (operation != null) {
operation.cancel(); uploadOperationQueue.remove(operation);
operation.cancel();
}
} else {
FileUploadOperation operation = uploadOperationPathsEnc.get(location);
if (operation != null) {
uploadOperationQueue.remove(operation);
operation.cancel();
}
} }
} }
}); });
...@@ -319,17 +328,39 @@ public class FileLoader { ...@@ -319,17 +328,39 @@ public class FileLoader {
Utilities.fileUploadQueue.postRunnable(new Runnable() { Utilities.fileUploadQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
if (key != null) {
if (uploadOperationPathsEnc.containsKey(location)) {
return;
}
} else {
if (uploadOperationPaths.containsKey(location)) {
return;
}
}
FileUploadOperation operation = new FileUploadOperation(location, key, iv); FileUploadOperation operation = new FileUploadOperation(location, key, iv);
uploadOperationPaths.put(location, operation); if (key != null) {
uploadOperationPathsEnc.put(location, operation);
} else {
uploadOperationPaths.put(location, operation);
}
operation.delegate = new FileUploadOperation.FileUploadOperationDelegate() { operation.delegate = new FileUploadOperation.FileUploadOperationDelegate() {
@Override @Override
public void didFinishUploadingFile(FileUploadOperation operation, final TLRPC.InputFile inputFile, final TLRPC.InputEncryptedFile inputEncryptedFile) { public void didFinishUploadingFile(FileUploadOperation operation, final TLRPC.InputFile inputFile, final TLRPC.InputEncryptedFile inputEncryptedFile) {
NotificationCenter.Instance.postNotificationName(FileDidUpload, location, inputFile, inputEncryptedFile);
fileProgresses.remove(location);
Utilities.fileUploadQueue.postRunnable(new Runnable() { Utilities.fileUploadQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
uploadOperationPaths.remove(location); Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
NotificationCenter.Instance.postNotificationName(FileDidUpload, location, inputFile, inputEncryptedFile);
fileProgresses.remove(location);
}
});
if (key != null) {
uploadOperationPathsEnc.remove(location);
} else {
uploadOperationPaths.remove(location);
}
currentUploadOperationsCount--; currentUploadOperationsCount--;
if (currentUploadOperationsCount < 2) { if (currentUploadOperationsCount < 2) {
FileUploadOperation operation = uploadOperationQueue.poll(); FileUploadOperation operation = uploadOperationQueue.poll();
...@@ -343,15 +374,24 @@ public class FileLoader { ...@@ -343,15 +374,24 @@ public class FileLoader {
} }
@Override @Override
public void didFailedUploadingFile(FileUploadOperation operation) { public void didFailedUploadingFile(final FileUploadOperation operation) {
fileProgresses.remove(location);
if (operation.state != 2) {
NotificationCenter.Instance.postNotificationName(FileDidFailUpload, location);
}
Utilities.fileUploadQueue.postRunnable(new Runnable() { Utilities.fileUploadQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
uploadOperationPaths.remove(location); Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
fileProgresses.remove(location);
if (operation.state != 2) {
NotificationCenter.Instance.postNotificationName(FileDidFailUpload, location, key != null);
}
}
});
if (key != null) {
uploadOperationPathsEnc.remove(location);
} else {
uploadOperationPaths.remove(location);
}
currentUploadOperationsCount--; currentUploadOperationsCount--;
if (currentUploadOperationsCount < 2) { if (currentUploadOperationsCount < 2) {
FileUploadOperation operation = uploadOperationQueue.poll(); FileUploadOperation operation = uploadOperationQueue.poll();
...@@ -375,7 +415,7 @@ public class FileLoader { ...@@ -375,7 +415,7 @@ public class FileLoader {
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
public void run() { public void run() {
NotificationCenter.Instance.postNotificationName(FileUploadProgressChanged, location, progress); NotificationCenter.Instance.postNotificationName(FileUploadProgressChanged, location, progress, key != null);
} }
}); });
} }
......
...@@ -8,9 +8,6 @@ ...@@ -8,9 +8,6 @@
package org.telegram.messenger; package org.telegram.messenger;
import org.telegram.TL.TLObject;
import org.telegram.TL.TLRPC;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.math.BigInteger; import java.math.BigInteger;
...@@ -134,7 +131,7 @@ public class FileUploadOperation { ...@@ -134,7 +131,7 @@ public class FileUploadOperation {
} }
System.arraycopy(readBuffer, 0, sendBuffer, 0, readed); System.arraycopy(readBuffer, 0, sendBuffer, 0, readed);
if (key != null) { if (key != null) {
sendBuffer = Utilities.aesIgeEncryption(sendBuffer, key, iv, true, true); sendBuffer = Utilities.aesIgeEncryption(sendBuffer, key, iv, true, true, 0);
} }
mdEnc.update(sendBuffer, 0, readed + toAdd); mdEnc.update(sendBuffer, 0, readed + toAdd);
if (isBigFile) { if (isBigFile) {
......
...@@ -9,20 +9,50 @@ ...@@ -9,20 +9,50 @@
package org.telegram.messenger; package org.telegram.messenger;
import android.app.Activity; import android.app.Activity;
import android.content.ComponentName; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver; import android.os.PowerManager;
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver { public class GcmBroadcastReceiver extends BroadcastReceiver {
public static final int NOTIFICATION_ID = 1; public static final int NOTIFICATION_ID = 1;
@Override @Override
public void onReceive(final Context context, final Intent intent) { public void onReceive(final Context context, final Intent intent) {
FileLog.d("tmessages", "GCM received intent: " + intent); FileLog.d("tmessages", "GCM received intent: " + intent);
ComponentName comp = new ComponentName(context.getPackageName(), GcmService.class.getName());
startWakefulService(context, (intent.setComponent(comp))); if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
wl.acquire();
// SharedPreferences preferences = context.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
// boolean globalEnabled = preferences.getBoolean("EnableAll", true);
// if (!globalEnabled) {
// FileLog.d("tmessages", "GCM disabled");
// return;
// }
Thread thread = new Thread(new Runnable() {
public void run() {
ConnectionsManager.Instance.resumeNetworkMaybe();
wl.release();
}
});
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
} else if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
String registration = intent.getStringExtra("registration_id");
if (intent.getStringExtra("error") != null) {
FileLog.e("tmessages", "Registration failed, should try again later.");
} else if (intent.getStringExtra("unregistered") != null) {
FileLog.e("tmessages", "unregistration done, new messages from the authorized sender will be rejected");
} else if (registration != null) {
FileLog.e("tmessages", "registration id = " + registration);
}
}
setResultCode(Activity.RESULT_OK); setResultCode(Activity.RESULT_OK);
} }
} }
/*
* This is the source code of Telegram for Android v. 1.3.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.
*/
package org.telegram.messenger;
import android.app.IntentService;
import android.content.Intent;
public class GcmService extends IntentService {
public GcmService() {
super("GcmService");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
// SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
// boolean globalEnabled = preferences.getBoolean("EnableAll", true);
// if (!globalEnabled) {
// FileLog.d("tmessages", "GCM disabled");
// return;
// }
ConnectionsManager.Instance.resumeNetworkMaybe();
} else if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
String registration = intent.getStringExtra("registration_id");
if (intent.getStringExtra("error") != null) {
FileLog.e("tmessages", "Registration failed, should try again later.");
} else if (intent.getStringExtra("unregistered") != null) {
FileLog.e("tmessages", "unregistration done, new messages from the authorized sender will be rejected");
} else if (registration != null) {
FileLog.e("tmessages", "registration id = " + registration);
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
}
...@@ -8,12 +8,9 @@ ...@@ -8,12 +8,9 @@
package org.telegram.messenger; package org.telegram.messenger;
import org.telegram.TL.TLClassStore;
import org.telegram.TL.TLObject;
import org.telegram.TL.TLRPC;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
...@@ -28,7 +25,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti ...@@ -28,7 +25,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
private byte[] authNewNonce; private byte[] authNewNonce;
private byte[] authKey; private byte[] authKey;
private byte[] authKeyId; private long authKeyId;
private boolean processedPQRes; private boolean processedPQRes;
...@@ -64,7 +61,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti ...@@ -64,7 +61,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
authServerNonce = null; authServerNonce = null;
authNewNonce = null; authNewNonce = null;
authKey = null; authKey = null;
authKeyId = null; authKeyId = 0;
processedPQRes = false; processedPQRes = false;
reqPQMsgData = null; reqPQMsgData = null;
reqDHMsgData = null; reqDHMsgData = null;
...@@ -325,7 +322,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti ...@@ -325,7 +322,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
System.arraycopy(authNewNonce, 0, newNonce0_4, 0, 4); System.arraycopy(authNewNonce, 0, newNonce0_4, 0, 4);
tmpAesIv.writeRaw(newNonce0_4); tmpAesIv.writeRaw(newNonce0_4);
byte[] answerWithHash = Utilities.aesIgeEncryption(serverDhParams.encrypted_answer, tmpAesKey.toByteArray(), tmpAesIv.toByteArray(), false, false); byte[] answerWithHash = Utilities.aesIgeEncryption(serverDhParams.encrypted_answer, tmpAesKey.toByteArray(), tmpAesIv.toByteArray(), false, false, 0);
byte[] answerHash = new byte[20]; byte[] answerHash = new byte[20];
System.arraycopy(answerWithHash, 0, answerHash, 0, 20); System.arraycopy(answerWithHash, 0, answerHash, 0, 20);
...@@ -401,8 +398,11 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti ...@@ -401,8 +398,11 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
authKey = correctedAuth; authKey = correctedAuth;
} }
byte[] authKeyHash = Utilities.computeSHA1(authKey); byte[] authKeyHash = Utilities.computeSHA1(authKey);
authKeyId = new byte[8]; byte[] authKeyArr = new byte[8];
System.arraycopy(authKeyHash, authKeyHash.length - 8, authKeyId, 0, 8); System.arraycopy(authKeyHash, authKeyHash.length - 8, authKeyArr, 0, 8);
ByteBuffer buffer = ByteBuffer.wrap(authKeyArr);
buffer.order(ByteOrder.LITTLE_ENDIAN);
authKeyId = buffer.getLong();
SerializedData serverSaltData = new SerializedData(); SerializedData serverSaltData = new SerializedData();
for (int i = 7; i >= 0; i--) { for (int i = 7; i >= 0; i--) {
...@@ -443,7 +443,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti ...@@ -443,7 +443,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
TLRPC.TL_set_client_DH_params setClientDhParams = new TLRPC.TL_set_client_DH_params(); TLRPC.TL_set_client_DH_params setClientDhParams = new TLRPC.TL_set_client_DH_params();
setClientDhParams.nonce = authNonce; setClientDhParams.nonce = authNonce;
setClientDhParams.server_nonce = authServerNonce; setClientDhParams.server_nonce = authServerNonce;
setClientDhParams.encrypted_data = Utilities.aesIgeEncryption(clientDataWithHash.toByteArray(), tmpAesKey.toByteArray(), tmpAesIv.toByteArray(), true, false); setClientDhParams.encrypted_data = Utilities.aesIgeEncryption(clientDataWithHash.toByteArray(), tmpAesKey.toByteArray(), tmpAesIv.toByteArray(), true, false, 0);
TLRPC.TL_msgs_ack msgsAck = new TLRPC.TL_msgs_ack(); TLRPC.TL_msgs_ack msgsAck = new TLRPC.TL_msgs_ack();
msgsAck.msg_ids = new ArrayList<Long>(); msgsAck.msg_ids = new ArrayList<Long>();
...@@ -590,21 +590,20 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti ...@@ -590,21 +590,20 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
} }
@Override @Override
public void tcpConnectionReceivedData(TcpConnection connection, byte[] data) { public void tcpConnectionReceivedData(TcpConnection connection, ByteBufferDesc data, int length) {
SerializedData is = new SerializedData(data);
long keyId = is.readInt64(); long keyId = data.readInt64();
if (keyId == 0) { if (keyId == 0) {
long messageId = is.readInt64(); long messageId = data.readInt64();
if (processedMessageIds.contains(messageId)) { if (processedMessageIds.contains(messageId)) {
FileLog.d("tmessages", String.format("===== Duplicate message id %d received, ignoring", messageId)); FileLog.d("tmessages", String.format("===== Duplicate message id %d received, ignoring", messageId));
return; return;
} }
int messageLength = is.readInt32(); int messageLength = data.readInt32();
int constructor = is.readInt32(); int constructor = data.readInt32();
TLObject object = TLClassStore.Instance().TLdeserialize(is, constructor); TLObject object = TLClassStore.Instance().TLdeserialize(data, constructor);
if (object != null) { if (object != null) {
processedMessageIds.add(messageId); processedMessageIds.add(messageId);
......
...@@ -8,8 +8,6 @@ ...@@ -8,8 +8,6 @@
package org.telegram.messenger; package org.telegram.messenger;
import org.telegram.TL.TLRPC;
public class NetworkMessage { public class NetworkMessage {
public TLRPC.TL_protoMessage protoMessage; public TLRPC.TL_protoMessage protoMessage;
public Object rawRequest; public Object rawRequest;
......
...@@ -8,9 +8,6 @@ ...@@ -8,9 +8,6 @@
package org.telegram.messenger; package org.telegram.messenger;
import org.telegram.TL.TLObject;
import org.telegram.TL.TLRPC;
import java.util.ArrayList; import java.util.ArrayList;
public class RPCRequest { public class RPCRequest {
......
...@@ -6,10 +6,7 @@ ...@@ -6,10 +6,7 @@
* Copyright Nikolai Kudashov, 2013. * Copyright Nikolai Kudashov, 2013.
*/ */
package org.telegram.TL; package org.telegram.messenger;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.SerializedData;
import java.util.HashMap; import java.util.HashMap;
...@@ -317,6 +314,7 @@ public class TLClassStore { ...@@ -317,6 +314,7 @@ public class TLClassStore {
classStore.put(TLRPC.TL_req_DH_params.constructor, TLRPC.TL_req_DH_params.class); classStore.put(TLRPC.TL_req_DH_params.constructor, TLRPC.TL_req_DH_params.class);
classStore.put(TLRPC.TL_set_client_DH_params.constructor, TLRPC.TL_set_client_DH_params.class); classStore.put(TLRPC.TL_set_client_DH_params.constructor, TLRPC.TL_set_client_DH_params.class);
classStore.put(TLRPC.TL_ping.constructor, TLRPC.TL_ping.class); classStore.put(TLRPC.TL_ping.constructor, TLRPC.TL_ping.class);
classStore.put(TLRPC.TL_ping_delay_disconnect.constructor, TLRPC.TL_ping_delay_disconnect.class);
classStore.put(TLRPC.TL_destroy_session.constructor, TLRPC.TL_destroy_session.class); classStore.put(TLRPC.TL_destroy_session.constructor, TLRPC.TL_destroy_session.class);
classStore.put(TLRPC.TL_destroy_sessions.constructor, TLRPC.TL_destroy_sessions.class); classStore.put(TLRPC.TL_destroy_sessions.constructor, TLRPC.TL_destroy_sessions.class);
classStore.put(TLRPC.TL_get_future_salts.constructor, TLRPC.TL_get_future_salts.class); classStore.put(TLRPC.TL_get_future_salts.constructor, TLRPC.TL_get_future_salts.class);
...@@ -408,6 +406,8 @@ public class TLClassStore { ...@@ -408,6 +406,8 @@ public class TLClassStore {
classStore.put(TLRPC.TL_messages_sendEncryptedService.constructor, TLRPC.TL_messages_sendEncryptedService.class); classStore.put(TLRPC.TL_messages_sendEncryptedService.constructor, TLRPC.TL_messages_sendEncryptedService.class);
classStore.put(TLRPC.TL_messages_receivedQueue.constructor, TLRPC.TL_messages_receivedQueue.class); classStore.put(TLRPC.TL_messages_receivedQueue.constructor, TLRPC.TL_messages_receivedQueue.class);
classStore.put(TLRPC.TL_upload_saveBigFilePart.constructor, TLRPC.TL_upload_saveBigFilePart.class); classStore.put(TLRPC.TL_upload_saveBigFilePart.constructor, TLRPC.TL_upload_saveBigFilePart.class);
classStore.put(TLRPC.TL_help_support.constructor, TLRPC.TL_help_support.class);
classStore.put(TLRPC.TL_help_getSupport.constructor, TLRPC.TL_help_getSupport.class);
classStore.put(TLRPC.TL_msg_container.constructor, TLRPC.TL_msg_container.class); classStore.put(TLRPC.TL_msg_container.constructor, TLRPC.TL_msg_container.class);
classStore.put(TLRPC.TL_fileEncryptedLocation.constructor, TLRPC.TL_fileEncryptedLocation.class); classStore.put(TLRPC.TL_fileEncryptedLocation.constructor, TLRPC.TL_fileEncryptedLocation.class);
...@@ -434,7 +434,7 @@ public class TLClassStore { ...@@ -434,7 +434,7 @@ public class TLClassStore {
return store; return store;
} }
public TLObject TLdeserialize(SerializedData stream, int constructor) { public TLObject TLdeserialize(AbsSerializedData stream, int constructor) {
try { try {
return TLdeserialize(stream, constructor, null); return TLdeserialize(stream, constructor, null);
} catch (Exception e) { } catch (Exception e) {
...@@ -442,7 +442,7 @@ public class TLClassStore { ...@@ -442,7 +442,7 @@ public class TLClassStore {
} }
} }
public TLObject TLdeserialize(SerializedData stream, int constructor, TLObject request) { public TLObject TLdeserialize(AbsSerializedData stream, int constructor, TLObject request) {
Class objClass = classStore.get(constructor); Class objClass = classStore.get(constructor);
if (objClass != null) { if (objClass != null) {
try { try {
......
...@@ -6,16 +6,14 @@ ...@@ -6,16 +6,14 @@
* Copyright Nikolai Kudashov, 2013. * Copyright Nikolai Kudashov, 2013.
*/ */
package org.telegram.TL; package org.telegram.messenger;
import org.telegram.messenger.SerializedData;
public class TLObject { public class TLObject {
public TLObject () { public TLObject () {
} }
public void readParams(SerializedData stream) { public void readParams(AbsSerializedData stream) {
} }
...@@ -23,7 +21,7 @@ public class TLObject { ...@@ -23,7 +21,7 @@ public class TLObject {
return null; return null;
} }
public void serializeToStream(SerializedData stream) { public void serializeToStream(AbsSerializedData stream) {
} }
...@@ -35,7 +33,11 @@ public class TLObject { ...@@ -35,7 +33,11 @@ public class TLObject {
return 11; return 11;
} }
public void parseVector(TLRPC.Vector vector, SerializedData data) { public void parseVector(TLRPC.Vector vector, AbsSerializedData data) {
}
public void freeResources() {
} }
} }
...@@ -12,8 +12,6 @@ import android.content.Context; ...@@ -12,8 +12,6 @@ import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.util.Base64; import android.util.Base64;
import org.telegram.TL.TLClassStore;
import org.telegram.TL.TLRPC;
import org.telegram.ui.ApplicationLoader; import org.telegram.ui.ApplicationLoader;
import java.io.File; import java.io.File;
...@@ -30,6 +28,7 @@ public class UserConfig { ...@@ -30,6 +28,7 @@ public class UserConfig {
public static String importHash = ""; public static String importHash = "";
private final static Integer sync = 1; private final static Integer sync = 1;
public static boolean saveIncomingPhotos = false; public static boolean saveIncomingPhotos = false;
public static int contactsVersion = 1;
public static int getNewMessageId() { public static int getNewMessageId() {
int id; int id;
...@@ -49,14 +48,15 @@ public class UserConfig { ...@@ -49,14 +48,15 @@ public class UserConfig {
try { try {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("userconfing", Context.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("userconfing", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit(); SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("registeredForPush", registeredForPush);
editor.putString("pushString", pushString);
editor.putInt("lastSendMessageId", lastSendMessageId);
editor.putInt("lastLocalId", lastLocalId);
editor.putString("contactsHash", contactsHash);
editor.putString("importHash", importHash);
editor.putBoolean("saveIncomingPhotos", saveIncomingPhotos);
editor.putInt("contactsVersion", contactsVersion);
if (currentUser != null) { if (currentUser != null) {
editor.putBoolean("registeredForPush", registeredForPush);
editor.putString("pushString", pushString);
editor.putInt("lastSendMessageId", lastSendMessageId);
editor.putInt("lastLocalId", lastLocalId);
editor.putString("contactsHash", contactsHash);
editor.putString("importHash", importHash);
editor.putBoolean("saveIncomingPhotos", saveIncomingPhotos);
if (withFile) { if (withFile) {
SerializedData data = new SerializedData(); SerializedData data = new SerializedData();
currentUser.serializeToStream(data); currentUser.serializeToStream(data);
...@@ -66,13 +66,6 @@ public class UserConfig { ...@@ -66,13 +66,6 @@ public class UserConfig {
editor.putString("user", userString); editor.putString("user", userString);
} }
} else { } else {
editor.putBoolean("registeredForPush", registeredForPush);
editor.putString("pushString", pushString);
editor.putInt("lastSendMessageId", lastSendMessageId);
editor.putInt("lastLocalId", lastLocalId);
editor.putString("contactsHash", contactsHash);
editor.putString("importHash", importHash);
editor.putBoolean("saveIncomingPhotos", saveIncomingPhotos);
editor.remove("user"); editor.remove("user");
} }
editor.commit(); editor.commit();
...@@ -107,13 +100,7 @@ public class UserConfig { ...@@ -107,13 +100,7 @@ public class UserConfig {
contactsHash = data.readString(); contactsHash = data.readString();
importHash = data.readString(); importHash = data.readString();
saveIncomingPhotos = data.readBool(); saveIncomingPhotos = data.readBool();
if (currentUser.status != null) { contactsVersion = 0;
if (currentUser.status.expires != 0) {
currentUser.status.was_online = currentUser.status.expires;
} else {
currentUser.status.expires = currentUser.status.was_online;
}
}
MessagesStorage.lastQtsValue = data.readInt32(); MessagesStorage.lastQtsValue = data.readInt32();
MessagesStorage.lastSecretVersion = data.readInt32(); MessagesStorage.lastSecretVersion = data.readInt32();
int val = data.readInt32(); int val = data.readInt32();
...@@ -141,6 +128,7 @@ public class UserConfig { ...@@ -141,6 +128,7 @@ public class UserConfig {
contactsHash = preferences.getString("contactsHash", ""); contactsHash = preferences.getString("contactsHash", "");
importHash = preferences.getString("importHash", ""); importHash = preferences.getString("importHash", "");
saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false); saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false);
contactsVersion = preferences.getInt("contactsVersion", 0);
} }
if (lastLocalId > -210000) { if (lastLocalId > -210000) {
lastLocalId = -210000; lastLocalId = -210000;
...@@ -166,6 +154,7 @@ public class UserConfig { ...@@ -166,6 +154,7 @@ public class UserConfig {
contactsHash = preferences.getString("contactsHash", ""); contactsHash = preferences.getString("contactsHash", "");
importHash = preferences.getString("importHash", ""); importHash = preferences.getString("importHash", "");
saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false); saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false);
contactsVersion = preferences.getInt("contactsVersion", 0);
String user = preferences.getString("user", null); String user = preferences.getString("user", null);
if (user != null) { if (user != null) {
byte[] userBytes = Base64.decode(user, Base64.DEFAULT); byte[] userBytes = Base64.decode(user, Base64.DEFAULT);
...@@ -193,6 +182,7 @@ public class UserConfig { ...@@ -193,6 +182,7 @@ public class UserConfig {
importHash = ""; importHash = "";
lastLocalId = -210000; lastLocalId = -210000;
lastSendMessageId = -210000; lastSendMessageId = -210000;
contactsVersion = 1;
saveIncomingPhotos = false; saveIncomingPhotos = false;
saveConfig(true); saveConfig(true);
MessagesController.Instance.deleteAllAppAccounts(); MessagesController.Instance.deleteAllAppAccounts();
......
...@@ -11,7 +11,7 @@ package org.telegram.objects; ...@@ -11,7 +11,7 @@ package org.telegram.objects;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import org.telegram.TL.TLRPC; import org.telegram.messenger.TLRPC;
import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLoader;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -62,7 +62,7 @@ public class PhotoObject { ...@@ -62,7 +62,7 @@ public class PhotoObject {
for (TLRPC.PhotoSize obj : sizes) { for (TLRPC.PhotoSize obj : sizes) {
int diffW = Math.abs(obj.w - width); int diffW = Math.abs(obj.w - width);
int diffH = Math.abs(obj.h - height); int diffH = Math.abs(obj.h - height);
if (closestObject == null || closestWidth > diffW && closestHeight > diffH) { if (closestObject == null || closestWidth > diffW || closestHeight > diffH) {
closestObject = obj; closestObject = obj;
closestWidth = diffW; closestWidth = diffW;
closestHeight = diffH; closestHeight = diffH;
......
...@@ -22,7 +22,7 @@ import android.view.inputmethod.EditorInfo; ...@@ -22,7 +22,7 @@ import android.view.inputmethod.EditorInfo;
import android.widget.EditText; import android.widget.EditText;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.TL.TLRPC; import org.telegram.messenger.TLRPC;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
......
...@@ -25,7 +25,7 @@ import android.widget.EditText; ...@@ -25,7 +25,7 @@ import android.widget.EditText;
import android.widget.ImageButton; import android.widget.ImageButton;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.TL.TLRPC; import org.telegram.messenger.TLRPC;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationCenter;
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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